标签:
死锁的实例
package day11_second; public class DeathLock { public static void main(String[] args) { // TODO Auto-generated method stub DeathLocked1 dl1 = new DeathLocked1(); DeathLocked2 dl2 = new DeathLocked2(); Thread t1 = new Thread(dl1); Thread t2 = new Thread(dl2); t1.start(); t2.start(); } } class Res { public static Object obj1 = new Object(); public static Object obj2 = new Object(); } class DeathLocked1 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub fun(); } private void fun() { // TODO Auto-generated method stub synchronized (Res.obj1) { try {Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (Res.obj2) { System.out.println("在obj1中调用obj2"); } } } } class DeathLocked2 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub fun(); } private void fun() { // TODO Auto-generated method stub synchronized (Res.obj2) { try {Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (Res.obj1) { System.out.println("在obj2中调用obj1"); } } } }
当启动线程t1后,执行t1的fun方法,占用o1资源,然后t1休眠确保能够让t2来执行。t2执行fun()方法,占有o2资源。此时就形成了死锁产生的第四个必要条件。即线程t1占有了t2所需的资源,t2占有了t1所需的资源,双方都不释放,即形成死锁。
http://my.oschina.net/u/1469592/blog/208374
标签:
原文地址:http://www.cnblogs.com/childhooding/p/4741698.html