importjava.util.Random;publicclassTest1{publicstaticinttestV=0;publicstaticvoidmain(String[]args){doSomethingt1=newdoSomething(true);doSomethingt2=newdoSomething(false);n...
import java.util.Random;
public class Test1 {
public static int testV = 0;
public static void main(String[] args) {
doSomething t1 = new doSomething(true);
doSomething t2 = new doSomething(false);
new Thread(t1).start();
new Thread(t2).start();
}
}
class doSomething implements Runnable {
private boolean opera;
public doSomething(boolean opera) {
this.opera = opera;
}
@Override
public void run() {
while (true) {
if (opera) {
Test1.testV++;
System.out.println("加一之后:" + Test1.testV);
} else {
Test1.testV--;
System.out.println("减一之后:" + Test1.testV);
}
try {
// 挂起随机时间
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
为什么这段代码结果的前两行结果为下面呢?
减一之后:0
加一之后:0
展开