Java多线程死锁实例

来源:互联网 发布:python vim 配置 编辑:程序博客网 时间:2024/06/11 10:49

循环等待,产生死锁。

public class DeadLock {public static void main(String[]args){Resource r1=new Resource();Resource r2=new Resource();Thread t1=new MyThread1(r1, r2);Thread t2=new MyThread2(r1, r2);t1.start();t2.start();}}
public class MyThread1 extends Thread {Resource r1,r2;public MyThread1(Resource r1,Resource r2){this.r1=r1;this.r2=r2;}public void run(){while(true){synchronized (r1) {System.out.println("t1 get r1, wait r2");synchronized (r2) {System.out.println("t1 get r2");}}}}}
public class MyThread2 extends Thread {Resource r1,r2;public MyThread2(Resource r1,Resource r2){this.r1=r1;this.r2=r2;}public void run(){while(true){synchronized (r2) {System.out.println("t2 get r2, wait r1");synchronized (r1) {System.out.println("t2 get r1");}}}}}
public class Resource {int i;}

0 0