public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
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();
System.out.println(tt.b);
}
}
的运行结果是什么啊?是怎么运行的啊
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
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();
System.out.println(tt.b);
}
}
的运行结果是什么啊?是怎么运行的啊
1000
b = 1000执行顺序看注释:
public class TT implements Runnable{
int b = 100; public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000; // 4
Thread.sleep(5000); // 5
System.out.println("b = " + b); // 7
} public synchronized void m2() throws Exception{
Thread.sleep(2500); // 2
b = 2000; // 3
} public void run(){
try {
m1();
}
catch(Exception e) {
e.printStackTrace();
}
} static TT tt = new TT();
public static void main(String[] args) throws Exception{
Thread t = new Thread(tt);
t.start(); tt.m2(); // 1
System.out.println(tt.b); // 6
}
}从2到4因为同步关系,线程会等待,跑完3之后才能4.
比如 m2() 是synchronized
Thread.sleep(2500); 睡 2500毫秒
这个时候其他线程打断不了这个线程
也就是说无论睡多久其他线程都要等这个线程结束后才能开始
如果不是synchronized的 可能在睡的同时 其他线程可以运行
但是结果是不唯一的,在我的机器上cpu空闲时为:
2000
b=1000
忙时还出现过:
1000
b=1000