//过多的同步方法可能造成死锁
public class SynDemo03 {
public static void main(String[] args) {
Object g=new Object();
Object m=new Object();
Test t1=new Test(g, m);
Test2 t2=new Test2(g, m);
Thread proxy=new Thread(t1);//Runnable proxy=new Thread(t1);多态不能调用新增方法
Thread proxy2=new Thread(t2);
proxy.start();
proxy2.start();
}
}
class Test implements Runnable{
Object goods;
Object money;
//
public Test(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
public Object getGoods() {
return goods;
}
public void setGoods(Object goods) {
this.goods = goods;
}
public Object getMoney() {
return money;
}
public void setMoney(Object money) {
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized (money) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (goods) {
}
}
System.out.println("一手给货。。。。");
}
}
class Test2 implements Runnable{
Object goods;
Object money;
///
public Test2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
public Object getGoods() {
return goods;
}
public void setGoods(Object goods) {
this.goods = goods;
}
public Object getMoney() {
return money;
}
public void setMoney(Object money) {
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized (goods) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (money) {
}
}
System.out.println("一手给钱。。。。");
}
}
[线程]——死锁
最新推荐文章于 2022-06-14 10:29:26 发布