多线程 互斥锁

来源:互联网 发布:新加坡高中留学 知乎 编辑:程序博客网 时间:2024/05/20 19:18
package com.yys.thread;/** * Created by yys on 2017/9/25. * 两个线程执行 t1如果能拿到02对象则t1线程执行完毕    t2如果能拿到o1对象则t2线程执行完毕 * 现在两个线程分别锁定了对方需要的对象 造成线程死锁 */public class TestDeadLock implements Runnable{    public int flage = 1;    static Object o1 = new Object(), o2 = new Object();    @Override    public void run() {        System.out.println("flage=" + flage);        if(flage == 1){            synchronized (o1){                try {                    Thread.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                synchronized (o2){                    System.out.print("1");                }            }        }        if(flage == 0){            synchronized (o2){                try {                    Thread.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                synchronized (o1){                    System.out.print("0");                }            }        }    }    public static void main(String[] args){        TestDeadLock td1 = new TestDeadLock();        TestDeadLock td2 = new TestDeadLock();        td1.flage = 1;        td2.flage = 0;        Thread t1 = new Thread(td1);        Thread t2 = new Thread(td2);        t1.start();        t2.start();    }}