您的位置:首页 > 编程语言 > Java开发

java中的线程死锁的一个例子

2012-07-23 16:18 393 查看
class DeadLock

{

public static void main(String[] args) {

final Object resource1 = "resource1";

final Object resource2 = "resource2";

// t1 tries to lock resource1 then resource2

Thread t1 = new Thread() {

public void run() {

// Lock resource 1

synchronized (resource1) {

System.out.println("Thread 1: locked resource 1");

try {

Thread.sleep(50);

} catch (InterruptedException 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(50);

} catch (InterruptedException e) {

}

synchronized (resource1) {

System.out.println("Thread 2: locked resource 1");

}

}

}

};

// If all goes as planned, deadlock will occur,

// and the program will never exit.

t1.start();

t2.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: