java实现死锁的demo

只有当t1线程占用o1且正好也需要o2,t2此时占用o2且正好也需要o1的时候才会出现死锁,(类似于2个人拿着两个筷子吃饭,都是需要对方的一根筷子才能吃)

以下代码t1线程占用o1,并且获取到o2对象后才会释放o1,而t2线程先占用o2又去获取o1,而此时的o1被t1线程占用,o2被t2线程占用,t1和t2都在无限等待,就会出现死锁。

package javasimple; /** * 死锁demo * @author haokui * */ public class DieSynchronized { public static void main(String[] args) { /** * 创建并启动两个线程t1、t2。两个线程都要共享o1、o2两个对象 */ Object o1 = new Object(); Object o2 = new Object(); Thread t1 = new Thread(new T1(o1,o2)); Thread t2 = new Thread(new T2(o1,o2)); t1.start(); t2.start(); } } //创建两个线程类 class T1 implements Runnable { Object o1; Object o2; public T1(Object o1, Object o2){ this.o1 = o1; this.o2 = o2; } public void run() { //锁o1和o2 synchronized (o1) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (o2) { System.out.println("o2"); } } } } class T2 implements Runnable { Object o1; Object o2; public T2(Object o1, Object o2){ this.o1 = o1; this.o2 = o2; } public void run() { synchronized (o2) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (o1) { System.out.println("o1"); } } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppfdz.html