java多线程之死锁

来源:互联网 发布:windows.h在哪 编辑:程序博客网 时间:2024/06/05 18:46

概念:当所有的线程都在等待得到某个资源后才能继续运行下去时,整个程序将被挂起,这种情况叫做死锁。

死锁的原因:互相等待,就是你等我来我等你。或者理解为互不相让。如图所示:


注:note代表本子,pen代表笔。

这张图的意思是:线程1需要线程2的笔才能写字,线程2需要线程1的本子才能写字,但是它们互不相让,互相等待,就会死锁。

在java中,同步代码块的嵌套是最容易发生死锁的。

示例代码:

/* *线程A */class AThread implements Runnable {private Object pen;private Object note;public AThread(Object pen, Object note) {this.pen = pen;this.note = note;}@Overridepublic void run() {// 先获得笔 --- 再获得本synchronized (pen) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}synchronized (note) {System.out.println("A 写字");}}}}
========================

/* *线程B */class BThread implements Runnable {private Object pen;private Object note;public BThread(Object pen, Object note) {this.pen = pen;this.note = note;}@Overridepublic void run() {// 先获得 本 --- 再获得笔synchronized (note) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}synchronized (pen) {System.out.println("B 写字");}}}}
==============================

/* *主线程 */public class DeadLockTest {public static void main(String[] args) {Object pen = new Object();// 笔Object note = new Object(); // 本new Thread(new AThread(pen, note)).start();new Thread(new BThread(pen, note)).start();}}

运行后,程序没人任何结果,但也不会结束,会死死的卡住不动。