一个线程问题求解
public class Machine implements Runnable{
private int a=0;
public void run(){
for(a=0;a<50;a++){
System.out.println(Thread.currentThread().getName()+":"+a);
try{
Thread.sleep(100);
}catch(InterruptedException e){throw new RuntimeException(e);}
}
}
public static void main(String args[]){
Machine machine=new Machine();
Thread t1=new Thread(machine);
Thread t2=new Thread(machine);
t1.start();
t2.start();
}
} 这个打印结果为什么a=0有2次?
[解决办法]
public class Machine implements Runnable{
private int a=0;
private Object object=new Object();
public void run(){
synchronized (object) {
for(a=0;a<50;a++){
System.out.println(Thread.currentThread().getName()+":"+a);
try{
Thread.sleep(100);
}catch(InterruptedException e){throw new RuntimeException(e);}
}
}
}
public static void main(String args[]){
Machine machine=new Machine();
Thread t1=new Thread(machine);
Thread t2=new Thread(machine);
t1.start();
t2.start();
}
}