Java演示死锁代码
Posted haha
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java演示死锁代码相关的知识,希望对你有一定的参考价值。
死锁代码
public class DeadLock {
final Object lockA = new Object();
final Object lockB = new Object();
public static void main(String[] args) {
DeadLock demo = new DeadLock();
demo.startLock();
}
public void startLock() {
ThreadA a = new ThreadA(lockA, lockB);
ThreadB b = new ThreadB(lockA, lockB);
// start threads
a.start();
b.start();
}
}
class ThreadA extends Thread {
private Object lockA = null;
private Object lockB = null;
public ThreadA(Object a, Object b) {
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockA) {
System.out.println("*** Thread A: ***: Lock A");
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB) {
System.out.println("*** Thread A: ***: Lock B");
}
}
System.out.println("*** Thread A: ***: Finished");
}
}
class ThreadB extends Thread {
private Object lockA = null;
private Object lockB = null;
public ThreadB(Object a, Object b) {
this.lockA = a;
this.lockB = b;
}
public void run() {
synchronized (lockB) {
System.out.println("*** Thread B: ***: Lock B");
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockA) {
System.out.println("*** Thread B: ***: Lock A");
}
}
System.out.println("*** Thread B: ***: Finished");
}
}
控制台截图:
以上是关于Java演示死锁代码的主要内容,如果未能解决你的问题,请参考以下文章