其实死锁很好理解,比如一个人要进入两个房间,但是这两个房间都是每次只能进入一个人,而且还是只能等里面的人办完事之后才能有另一个人进入
转化为多线程就是:
1.给这两个房间加一个class锁
2. 让一个人张三在房间A的时候尝试获取房间B的锁
3. 让李四在房间B的时候,尝试获取A的锁
4. 这样就会造成死锁
下面代码中注释掉的部分加上不加上都可以
package duoxiancheng.thread;
public class Test {
/*
死锁,可以用Java bin里面的jconsole.exe来查看是否有死锁
*/
public static synchronized void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (B.class) {
// try {
// System.out.println("111");
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println("4");
// e.printStackTrace();
// }
System.out.println("5");
synchronized (A.class) {
}
}
}
},"线程AA").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (A.class) {
// try {
// System.out.println(222);
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println("3");
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
System.out.println("6");
synchronized (B.class) {
}
}
}
},"线程BB").start();
}
}
class A {
}
class B {
}