Java线程:并发合作-死锁[Java编程]
本文“Java线程:并发合作-死锁[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
发死活锁的缘由普通是两个对象的锁彼此等候造成的.
在《Java线程:线程的同步与锁》一文中,简述死锁的概念与简单例子,但是所给的例子是不完好的,这里给出一个完好的例子.
/**
* Java线程:并发合作-死锁
*
* @author Administrator
*/
public class Test {
public static void main(String[] args) {
DeadlockRisk dead = new DeadlockRisk();
MyThread t1 = new MyThread(dead, 1, 2);
MyThread t2 = new MyThread(dead, 3, 4);
MyThread t3 = new MyThread(dead, 5, 6);
MyThread t4 = new MyThread(dead, 7, 8);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MyThread extends Thread {
private DeadlockRisk dead;
private int a, b;
MyThread(DeadlockRisk dead, int a, int b) {
this.dead = dead;
this.a = a;
this.b = b;
}
@Override
public void run() {
dead.read();
dead.write(a, b);
}
}
class DeadlockRisk {
private static class Resource {
public int value;
}
private Resource resourceA = new Resource();
private Resource resourceB = new Resource();
public int read() {
synchronized (resourceA) {
System.out.println("read():" + Thread.currentThread().getName() + "获得了resourceA的锁!");
synchronized (resourceB) {
System.out.println("read():" + Thread.currentThread().getName() + "获得了resourceB的锁!");
return resourceB.value + resourceA.value;
}
}
}
public void write(int a, int b) {
synchronized (resourceB) {
System.out.println("write():" + Thread.currentThread().getName() + "获得了resourceA的锁!");
synchronized (resourceA) {
System.out.println("write():" + Thread.currentThread().getName() + "获得了resourceB的锁!");
resourceA.value = a;
resourceB.value = b;
}
}
}
}
下面死锁的情形发生了,真是可贵一见啊:
出处:http://lavasoft.blog.51cto.com/62575/222074
以上是“Java线程:并发合作-死锁[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |