MultiThread/multithreading_init/src/main/java/thread_1/safe1/SafeCounter.java

38 lines
984 B
Java
Raw Normal View History

package thread_1.safe1;
import lombok.Getter;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Getter
public class SafeCounter {
private static final Lock lock = new ReentrantLock();
private static Integer count = 0;
public static void main(String[] args) throws InterruptedException {
// 创建 1000 个线程并进行计数
Thread[] threads = new Thread[1000];
for (int i = 0; i < 1000; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
lock.lock();
count++;
lock.unlock();
}
});
threads[i].start();
}
// 等待所有线程完成
for (int i = 0; i < 1000; i++) {
threads[i].join();
}
// 输出最终计数值
System.out.println("Count: " + count); // 结果应该等于 1000000
}
}