就是要创建100个线程,每个线程都对sum值进行加一,如果我注释掉sleep(1);的话就会输出0 没有注释掉就会正常输出1-100请问 这是为什么啊?谢谢。
public class test1 {
private static int sum=0;
private static Object obj=new Object();
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<100;i++){
synchronized(obj){
myThread mythread=new myThread(sum);
mythread.start();
Thread.sleep(1);
sum=mythread.getSum();
System.out.println(sum);
}
}
}
}
class myThread extends Thread{
public int sum;
public myThread(int sum){
this.sum=sum;
}
public void run(){
synchronized(this){
sum++;
}
}
public int getSum(){
return sum;
}
}