我在没有同步的情况下通过 100 个不同的线程递增静态变量,但最终结果为 100。我已经多次运行此代码并得到相同的结果。那么我的代码不需要同步吗?我正在使用 BlueJ IDE 运行代码
public class Main {
private final static int MAX_THREADS = 100;
public static void main(String[] args) {
Thread[] threads = new Thread[MAX_THREADS];
for(int i=0; i<MAX_THREADS; i++) {
threads[i] = new Thread(new Job(), "Thread-" + i);
threads[i].start();
try{
Thread.sleep((int)(Math.random() * 1000));
}catch(InterruptedException e) {
e.printStackTrace();
}
}
for(int i=0; i<MAX_THREADS; i++) {
try {
threads[i].join();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf("Final Value: %d\n", Job.getSuccessCount());
}
}
public class Job implements Runnable {
private static int successCount;
public static int getSuccessCount() {return successCount;}
@Override
public void run() {
System.out.printf("%s: Incrementing successCount %d\n", Thread.currentThread().getName(), successCount);
try{
Thread.sleep((int)(Math.random() * 10000));
}catch(InterruptedException e) {
e.printStackTrace();
}
successCount++;
System.out.printf("%s: Incrementing Complete %d\n", Thread.currentThread().getName(), successCount);
}
}
最佳答案
基本上在您的代码中,由于 sleep
语句(在线程中和启动器中),您可以有效地启动线程,从而有大量的非繁忙时间进行更新。这就是它起作用的原因。如果您的代码确实是多线程的,那么您将面临同步问题。
关于java - 在不同步的情况下通过 100 个不同的线程递增静态变量,但最终结果为 100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565648/