一个Java线程死锁的例子
package com.lk.B; public class Test4 { private static final Object o1 = new Object(); private static final Object o2 = new Object(); private class Run1 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub String threadName = Thread.currentThread().getName(); synchronized (o1) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(threadName+"进入同步块o1准备进入o2"); synchronized (o2) { System.out.println(threadName+"已经进入同步块o2"); } } } } private class Run2 implements Runnable{ @Override public void run() { // TODO Auto-generated method stub String threadName = Thread.currentThread().getName(); synchronized (o2) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(threadName+"进入同步块o2准备进入o1"); synchronized (o1) { System.out.println(threadName+"已经进入同步块o1"); } } } } public static void main(String[] args) { // TODO Auto-generated method stub Thread t1 = new Thread(new Test4().new Run1()); Thread t2 = new Thread(new Test4().new Run2()); t1.start(); t2.start(); } }
控制台的红色按钮笔试程序并没有运行结束,因为处于死锁状态
当程序启动后,第一个线程执行Run1类中的run方法,此时为o1加锁,然后线程休眠1s。然后第二个线程执行Run2类中的run方法,此时为o2加锁,然后线程休眠1s。此时第一个线程已经休眠结束,开始为o2加锁,而o2已经被加锁,因此发生了死锁。