下面程序的执行结果是什么,执行过程是怎样的,最好讲解下。。
public class TT implements Runnable{
int b=100;
public synchronized void m1() throws Exception{
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();
}
}
public class TT implements Runnable{
int b=100;
public synchronized void m1() throws Exception{
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();
}
}
执行过程是怎样的?那个synchronized 锁定的是什么?
int b=100;
public synchronized void m1() throws Exception{
b=1000;
Thread.sleep(5000);
System.out.println("b = "+b);
}
public synchronized void m2() throws Exception{
Thread.sleep(2500);
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();
Thread.sleep(1);
/*
* 这段程序你应该在这里睡一下来更清楚的了解执行路径,
* 因为两个线程到底谁的速度更快一些这个不好说,实际当中我测试时是主线程先拿到了m2的锁。
* 如果m2先拿到了锁,执行情况是这样的:
* 先睡眠2.5秒,这时m1执行,想要改变b的值,但他发现m2把b锁住了,所以必须等m2执行完。
* m2醒来后把b赋值成2000,等m2执行完m1开始执行并把b的值变成1000在打印出来。
* 我在m2后加了一个打印语句,打印结果应该是先打印m2的2000再打印m1的1000。
*
* 而如果我在主线程执行m2前先sleep一毫秒强制让t线程的m1执行,那么执行过程是这样的:
* 先执行m1,把b赋值为2000,然后开始睡5秒,然后m2执行,睡了2.5秒比m1先醒了,想改变b的值
* 这时候他发现m1锁住了,必须等m1执行完以后才能执行,所以又过了一会m1醒来,
* 打印出b的值1000,然后m2才执行,最后执行的是我加的那条打印语句,2000。
*
* 在实际中两个方法互锁了,只能执行一个,不会造成什么问题,但在测试时还是应该先确定一下到底是谁先执行的才好理解。
*/
tt.m2();
}
}