//这是一个会出现死锁的程序,但是不一定每次都会锁住
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.SynchronousQueue;
public class DeadLock {
public static void main(String[] args) {
boolean b = true;
TestDe tD1 = new TestDe("莱利", "五十万");
TestDe tD2 = new TestDe("莱利", "五十万");
Thread t1 = new Thread(tD1);
Thread t2 = new Thread(tD2);
tD1.b=true;
//当b=true时候,程序执行的是if(b)的内容;
t1.start();
tD2.b=false;
//当b=false时候,程序执行的是if(!b)的内容;
t2.start();
//当两个程序都在同时执行时候,tD1先把人给锁住,tD2先把钱给锁住。双方都在等待着对方放开手中的资源;
//这就会产生死锁
}
}
class TestDe implements Runnable{
public boolean b ;
private String person;
private String money;
TestDe(String person,String money) {
this.person = person;
this.money = money;
}
public void run() {
if(b) {
synchronized (person) {
System.out.println("给我钱, 我就放人。。。");
synchronized (money) {
System.out.println("先放人, 我在给钱。lalala。");
}
}
}
if(!b) {
synchronized (money) {
System.out.println("先放人, 我在给钱。。。");
synchronized (person) {
System.out.println("先给钱,在放人。lalala。");
}
}
}
}
}
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.SynchronousQueue;
public class DeadLock {
public static void main(String[] args) {
boolean b = true;
TestDe tD1 = new TestDe("莱利", "五十万");
TestDe tD2 = new TestDe("莱利", "五十万");
Thread t1 = new Thread(tD1);
Thread t2 = new Thread(tD2);
tD1.b=true;
//当b=true时候,程序执行的是if(b)的内容;
t1.start();
tD2.b=false;
//当b=false时候,程序执行的是if(!b)的内容;
t2.start();
//当两个程序都在同时执行时候,tD1先把人给锁住,tD2先把钱给锁住。双方都在等待着对方放开手中的资源;
//这就会产生死锁
}
}
class TestDe implements Runnable{
public boolean b ;
private String person;
private String money;
TestDe(String person,String money) {
this.person = person;
this.money = money;
}
public void run() {
if(b) {
synchronized (person) {
System.out.println("给我钱, 我就放人。。。");
synchronized (money) {
System.out.println("先放人, 我在给钱。lalala。");
}
}
}
if(!b) {
synchronized (money) {
System.out.println("先放人, 我在给钱。。。");
synchronized (person) {
System.out.println("先给钱,在放人。lalala。");
}
}
}
}
}