死锁面试真题

来源:互联网 发布:冬天饮品 知乎 编辑:程序博客网 时间:2024/05/02 06:12
//下面程序的运行结果为:
//1000
//b = 1000
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);
}
}


   /**************************************************************************************************/
//运行结果:
//2000
//b1 = 2000
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("b1 = " + b);
}
//核心:
/*one: 如果m1跟m2都加了synchronized,那么当其中一个在执行的时候,另外一个不能执行(例如m1在执行的时候,m2得等着m1执行结束,才能执行,可以理解成:m2也加了锁 但此时锁还在m1那里  所哟m2没有锁 只能等着m1执行完之后把锁让出来 m2才可以执行) 
two: 如果m1加了synchronized,但是m2没有加synchronized,这个时候 当m1在执行的时候 m2可以执行 */
public void synchronized m2() throws Exception {
Thread.sleep(3000);
b = 2000;
//System.out.println("b2 = " + 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(4000);
tt.m2();
System.out.println(tt.b);
}
}
0 0