Java 线程死锁

1 什么是Java线程死锁

Java中的死锁是多线程的一部分。当线程正在等待由另一个线程获取的对象锁而第二个线程正在等待由第一个线程获取的对象锁时,可能会发生死锁。由于两个线程都在互相等待释放锁,因此这种情况称为死锁

2 Java线程死锁的例子

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java 线程死锁的例子
 */
public class Demo {
    public static void main(String[] args) {
        final String resource1 = "eric";
        final String resource2 = "jack";
        // t1 tries to lock resource1 then resource2
        Thread t1 = new Thread() {
            public void run() {
                synchronized (resource1) {
                    System.out.println("Thread 1: locked resource 1");

                    try { Thread.sleep(100);} catch (Exception e) {}

                    synchronized (resource2) {
                        System.out.println("Thread 1: locked resource 2");
                    }
                }
            }
        };

        // t2 tries to lock resource2 then resource1
        Thread t2 = new Thread() {
            public void run() {
                synchronized (resource2) {
                    System.out.println("Thread 2: locked resource 2");

                    try { Thread.sleep(100);} catch (Exception e) {}

                    synchronized (resource1) {
                        System.out.println("Thread 2: locked resource 1");
                    }
                }
            }
        };


        t1.start();
        t2.start();
    }
}

输出结果为:

Thread 1: locked resource 1
Thread 2: locked resource 2

热门文章

优秀文章