public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
b = 2000;
System.out.println("b="+b);
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//调用 M1
tt.m2();
System.out.println(tt.b);
}
}
程序运行结果为什么是
b=2000
2000
b=1000搞不懂啊 为什么不先调用m1()这个方法啊 还有就是最后结果为什么是1000啊
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
b = 2000;
System.out.println("b="+b);
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//调用 M1
tt.m2();
System.out.println(tt.b);
}
}
程序运行结果为什么是
b=2000
2000
b=1000搞不懂啊 为什么不先调用m1()这个方法啊 还有就是最后结果为什么是1000啊
tt.m2();
System.out.println(tt.b);
这两个是按顺序来执行的,就是结果中一定是:
先输出b=2000,再输出2000。
2000
b=1000
这个结果啊 测试了 N次了 为啥啊
你可以在t.start();//调用 M1后加一句Thread.sleep(10);这样就是你想要的结果了。