黑马程序员技术交流社区
标题:
过多的同步容易造成死锁
[打印本页]
作者:
為了夢想
时间:
2015-7-25 14:08
标题:
过多的同步容易造成死锁
在多线程中,同一份资源在多个线程中都用了,可能会死锁,因为大家都不释放,举个例子:
public class Lockup {
public static void main(String[] args) {
Object m = new Object();
Object g = new Object();
Test t1 = new Test(g,m);
Test2 t2 = new Test2(g,m);
Thread th1 = new Thread(t1);
Thread th2 = new Thread(t2);
th1.start();
th2.start();
}
}
class Test implements Runnable{
Object goods ;
Object money ;
public Test(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized(goods){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(money){
}
}
System.out.println("一手给钱");
}
}
class Test2 implements Runnable{
Object goods ;
Object money ;
public Test2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized(money){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(goods){
}
}
System.out.println("一手给货");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2