黑马程序员技术交流社区
标题:
线程死锁小示例
[打印本页]
作者:
lu774374302
时间:
2015-8-21 10:14
标题:
线程死锁小示例
class DeadLock implements Runnable {
private Object resourceA = new Object();
private Object resourceB = new Object();
private int count = 0;
public void run() {
if(count++ < 1) {
synchronized(resourceA) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceA 的对象锁");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
synchronized(resourceB) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceB 的对象锁");
}
}
} else {
synchronized(resourceB) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceB 的对象锁");
try {
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
synchronized(resourceA) {
System.out.println(Thread.currentThread().getName() + "线程拿到了资源 resourceA 的对象锁");
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
DeadLock deadLock = new DeadLock();
Thread t1 = new Thread(deadLock);
Thread t2 = new Thread(deadLock);
t1.start();
t2.start();
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2