Thread-1:1000,2000Thread-0:2000,2000Thread-1:2000,1000Thread-0:1000,2000Thread-1:2000,1000Thread-0:1000,2000Thread-1:2000,1000Thread-0:1000,2000Thread-1:2000,1000Thread-0...
Thread-1:1000,2000
Thread-0:2000,2000
Thread-1:2000,1000
Thread-0:1000,2000
Thread-1:2000,1000
Thread-0:1000,2000
Thread-1:2000,1000
Thread-0:1000,2000
Thread-1:2000,1000
Thread-0:1000,2000
Thread-1:2000,1000
Thread-0:1000,2000
Thread-1:2000,1000
Thread-0:1000,2000
输出结果第二行 Thread-0:2000,2000 是怎么出来的?求分析,代码如下
public class JavaApp11 {
static class Box{
private int i=1000;
private int j=2000;
public void swap(){
int t=i;
Thread.yield();
i=j;
j=t;
}
public String toSring(){
return String.format("%d,%d",i,j);
}
}
static class St extends Thread{
private Box box;
St(Box box){
this.box=box;
}
public void run(){
for(int i=0;i<7;i++){
box.swap();
String x= box.toSring();
System.out.println(Thread.currentThread().getName()+":"+x);
}
}
}
public static void main(String[] args) {
Box box=new Box();
Thread t1=new St(box);
Thread t2=new St(box);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException ex) {}
}
}
展开