JavaSE 基础 第60节 死锁问题
2016-07-02
1 死锁问题
线程A现在占用资源2,需要请求资源1
线程B现在占用资源1,需要请求资源2
线程2获得了资源2
线程1获得了资源1
线程3获得了资源3
线程3在等待资源1
线程1在等待资源2
线程2在等待资源3
package com.java1995; /** * 资源类 * @author Administrator * */ public class Resource { String resourceName; public Resource(String resourceName){ this.resourceName=resourceName; } }
package com.java1995; /** * 线程类 * @author Administrator * */ public class MyThread extends Thread{ Resource r1; Resource r2; MyThread(Resource r1,Resource r2,String name){ super(name); this.r1=r1; this.r2=r2; } public void run(){ synchronized (r1) { System.out.println(this.getName()+"获得了"+r1.resourceName); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(this.getName()+"在等待"+r2.resourceName); synchronized (r2) { System.out.println(this.getName()+"获得了"+r2.resourceName); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
package com.java1995; /** * 测试类 * @author Administrator * */ public class Test { public static void main(String[] args) { Resource rs1=new Resource("资源1"); Resource rs2=new Resource("资源2"); Resource rs3=new Resource("资源3"); MyThread t1=new MyThread(rs1,rs2,"线程1"); MyThread t2=new MyThread(rs2,rs3,"线程2"); MyThread t3=new MyThread(rs3,rs1,"线程3"); t1.start(); t2.start(); t3.start(); } }
【参考资料】