码迷,mamicode.com
首页 > 编程语言 > 详细

java 第60节 死锁问题

时间:2016-07-02 15:57:46      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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();

    }

}

技术分享

 

【参考资料】

[1] Java轻松入门经典教程【完整版】

java 第60节 死锁问题

标签:

原文地址:http://www.cnblogs.com/cenliang/p/5635466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!