美文网首页
Java死锁的简单例子

Java死锁的简单例子

作者: SinX竟然被占用了 | 来源:发表于2017-09-07 22:31 被阅读0次

Java死锁的简单例子

两个线程互相占有对方需要的资源而不释放,便形成了死锁。

代码如下:
Program.java


/**
 * 程序类
 * @author michael
 *
 */
public class Program implements Runnable {
    
    //两个静态的资源
    public static Object obj1 = new Object();
    public static Object obj2 = new Object();
    
    //标志位
    public int flag = 1;    //1 or 2
    
    @Override
    public void run() {
        
        if(flag == 1) {
            synchronized (obj1) {
                System.out.println("flag: " + flag + ", 锁住了资源obj1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("flag: " + flag + ", 等待获取资源obj2");
                synchronized (obj2) {
                    System.out.println("flag: " + flag + ", 获得资源obj2");
                }
            }
        } else if(flag == 2) {
            synchronized (obj2) {
                System.out.println("flag: " + flag + ", 锁住了资源obj2");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("flag: " + flag + ", 等待获取资源obj1");
                synchronized (obj1) {
                    System.out.println("flag: " + flag + ", 获得资源obj1");
                }
            }
        }   
    }
        
}

DeadLock.java

DeadLock.java
/**
 * 死锁测试.
 * @author michael
 *
 */
public class DeadLock {
    
    public static void main(String[] args) {
        
        Program p1 = new Program();
        Program p2 = new Program();
        p1.flag = 1;
        p2.flag = 2;
        
        new Thread(p1).start();
        new Thread(p2).start();
        
    }
    
}

控制台结果:


这里写图片描述

相关文章

网友评论

      本文标题:Java死锁的简单例子

      本文链接:https://www.haomeiwen.com/subject/gguwjxtx.html