标签:多线程 死锁
原理: 线程A锁定对象B,线程C锁定对象D,线程A执行完毕需要还需要锁定对象D,同时线程C执行完毕还需要锁定对象B,大家相互等待,则造成死锁。
package com.roger.dead; /** * 线程死锁 * @author Roger */ public class TestDeadLock implements Runnable{ public int flag = 1; static Object o1 = new Object(); static Object o2 = new Object(); @Override public void run() { System.out.println("flag = "+ flag); if(flag == 1){ synchronized (o1) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o2) { System.out.println(1); } } } if(flag == 0){ synchronized (o2) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (o1) { System.out.println(0); } } } } public static void main(String[] args) { TestDeadLock test1 = new TestDeadLock(); TestDeadLock test2 = new TestDeadLock(); test1.flag = 1; test2.flag = 0; Thread t1 = new Thread(test1); Thread t2 = new Thread(test2); t1.start(); t2.start(); } }
本文出自 “10950988” 博客,请务必保留此出处http://10960988.blog.51cto.com/10950988/1791014
标签:多线程 死锁
原文地址:http://10960988.blog.51cto.com/10950988/1791014