Anu*_*bis 1 java synchronization
我正在尝试一个小程序来演示同步,但无论出于何种原因,它都没有达到我的期望.关键是要生成1000个线程,并将它们全部加1到静态Integer对象"sum".输出应该是1000但我得到不同的输出.这就像addSum()方法根本没有同步.我试过延迟println,认为它打印得太快但是这不是问题.我在这里错过了什么?
public class sumsync implements Runnable {
public static Integer sum = new Integer(0);
public sumsync(){
}
private synchronized void addSum(int i){
sum += i;
}
@Override
public void run() {
addSum(1);
}
}
Run Code Online (Sandbox Code Playgroud)
主要课程:
public class sumsyncinit {
private static final int max_threads = 1000;
public static void main(String[] args) {
sumsync task = new sumsync();
Thread thread;
for(int i=0; i<max_threads;i++){
thread = new Thread(task);
thread.start();
}
System.out.println(sumsync.sum);
}
}
Run Code Online (Sandbox Code Playgroud)