模拟死锁 java

来源:互联网 发布:手机专业绘画软件 编辑:程序博客网 时间:2024/06/04 00:35

直接上代码吧:

package com.sanhu.utils;public class DeckLockTest implements Runnable{    private int flag;    /**      * 这里必须使用static关键字进行修饰,来保证这两个对象对DeckLockTest的所有实例是共享的     * 如果不使用static修饰,不会产生死锁现象     */    private static Object o1 = new Object(), o2 = new Object();    public DeckLockTest(int flag) {        this.flag = flag;    }    @Override    public void run() {        System.err.println("start: " + flag);        if(flag == 1) {            synchronized (o1) {                try {                    Thread.sleep(500);                } catch (InterruptedException ie) {                    ie.printStackTrace();                }                synchronized (o2) {                    System.err.println(flag);                }            }        }        if(flag == 0) {            synchronized (o2) {                try {                    Thread.sleep(500);                } catch (InterruptedException ie) {                    ie.printStackTrace();                }                synchronized (o1) {                    System.err.println(flag);                }            }        }    }    public static void main(String[] args) {        DeckLockTest t1 = new DeckLockTest(1);        DeckLockTest t2 = new DeckLockTest(0);        new Thread(t1).start();        new Thread(t2).start();    }}

实现的关键是两个线程竞争两个锁。

原创粉丝点击