package 线程_180_线程_死锁_练习;
/**
-
过多的同步方法可能造成死锁测试
*/
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换成Thread Thread proxy2 = new Thread(t2); proxy.start();//,这里只有一个线程访问的是Object对象 proxy2.start(); System.out.println("测试线程是否被锁住");
}
}
/** -
加入try…catch是为了放大发生错误的可能性
/
class Test implements Runnable{//test测试;implements Runnable线程可运行状态,多线程
Object goods ;//goods商品
Object money ;//money钱
//构造器 ;通过外界传递进来
public Test(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {//run管理
while(true){
test();
}
}
public void test() {
//第一个锁
synchronized(goods){//synchronized同步;
try {
Thread.sleep(50);//Thread.sleep线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
//加第二个锁
synchronized(money){
}
}
System.out.println(“一手给钱”);
}
}
/*
*/
class Test2 implements Runnable{//test测试;implements Runnable线程可运行状态,多线程
Object goods ;//goods商品
Object money ;//money钱
//构造器 ;通过外界传递进来
public Test2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {//run管理
while(true){
test ();
}
}
public void test() {
synchronized(money){//synchronized同步
try {
Thread.sleep(50);//Thread.sleep线程休眠
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(goods){
}
}
System.out.println("一手给货");
}
}