public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(2500);
System.out.println("M1 b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(5000);
b = 2000;
System.out.println("M2 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();
tt.m2();
Thread.sleep(10000);
System.out.println(tt.b);
}
}
输出结果:
M2 b = 2000
M1 b = 1000
1000
为什么会先输出M2 b=2000,不是先执行了t.start()方法吗?
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(2500);
System.out.println("M1 b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(5000);
b = 2000;
System.out.println("M2 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();
tt.m2();
Thread.sleep(10000);
System.out.println(tt.b);
}
}
输出结果:
M2 b = 2000
M1 b = 1000
1000
为什么会先输出M2 b=2000,不是先执行了t.start()方法吗?
表示新起了一个线程,但是并不表示cpu要立即执行这个线程,有可能main函数的线程cpu时间片还没有完。这样就会执行tt.m2();就把tt锁住了。
t.start();后面加上
Thread.sleep(100);
可以确保t.start();后让main交出cpu时间片,这样就能轮到第二个线程运行m1()方法。