我在Java中编写了一个多线程程序,如下所示: -
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Counter counter = new Counter();
int val = counter.getValue();
while(val < 5){
val = counter.getValue();
System.out.println("In main thread : "+val);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Counter implements Runnable {
private int countValue;
Counter(){
countValue = 0;
Thread thread = new Thread(this ,"Counter A");
Thread thread1 = new Thread(this ,"Counter B");
thread.start();
thread1.start();
}
int getValue(){
return countValue;
}
@Override
public void run() {
// TODO Auto-generated method stub
while( countValue < 5){
System.out.println("In child thread : "+ ++countValue );
try {
Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
程序的输出是 输出: -
In main thread : 0
In child thread : 2
In child thread : 1
In child thread : 3
In child thread : 3
In child thread : 4
In child thread : 5
In main thread : 5
有人能详细解释一下这个输出是怎么来的。谢谢你提前
答案 0 :(得分:3)
你有3个线程(主线程和2个子线程)并行运行(除非你有一个proc盒子),它们都在读取和写入一个不受任何保护的资源countValue
同步。
当你做这样的事情时,你会得到明显的随机输出。