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

java学习笔记 死锁

时间:2016-08-28 01:14:13      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

在锁对象期间,会产生一个问题就是死锁,双方都在等在对方释放资源

范例:

public class Test {
    public static void main(String[] args) throws Exception {
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        mt1.flag = 1;
        mt2.flag = 2;
        Thread t1 = new Thread(mt1);
        Thread t2 = new Thread(mt2);        
        t1.start();
        t2.start();  
    }
}

class MyThread implements Runnable {
    static Object ob1 = new Object();//注意是static
    static Object ob2 = new Object();//注意是static
    int flag = 0;
  
    public void run() {
        if (flag == 1) {
            System.out.println("flag = 1");
            synchronized (ob1) {
                try {
                    Thread.sleep(1000);    
                }    catch (InterruptedException e) {
                    System.out.println("休眠中断");    
                }
                synchronized (ob2) {
                    System.out.println("1");    
                }
            }    
        }
        if (flag == 2) {
            System.out.println("flag = 2");
            synchronized (ob2) {
                try {
                    Thread.sleep(1000);    
                }    catch (InterruptedException e) {
                    System.out.println("休眠中断");    
                }
                synchronized (ob1) {
                    System.out.println("2");    
                }
            }            
        }    
    }
}

java学习笔记 死锁

标签:

原文地址:http://www.cnblogs.com/yhwsy/p/5814086.html

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