62,612
社区成员
发帖
与我相关
我的任务
分享
public class Test2 implements Runnable{
int b = 100;
public synchronized void m1() throws InterruptedException {
System.out.println("m1 is start");
b = 1000;
//Thread.sleep(5000);
System.out.println("m1.b="+b);
}
public synchronized void m2() throws InterruptedException { //去除synchronized后就是输出2000
System.out.println("m2 is start");
Thread.sleep(2000);
b=2000;
System.out.println("m2 is over");
}
public void run(){
try {
m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Test2 tt = new Test2();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println("main.b="+tt.b);
}
}
public static void main(String[] args) throws InterruptedException {
Test2 tt = new Test2();
Thread t = new Thread(tt);
t.start();
Thread.yield();
tt.m2();
System.out.println("main.b="+tt.b);
}
这样出来的结果就未必总是tt.m2()先执行了。