一、多个锁之间的嵌套产生死锁。
public class DaneLock {
public static void main(String[] args) {
DieLock d1=new DieLock(true);
DieLock d2=new DieLock(false);
Thread t1=new Thread(d1);
Thread t2=new Thread(d2);
t1.start();
t2.start();
}
}
class MyLock{
public static Object obj1=new Object();
public static Object obj2=new Object();
}
class DieLock implements Runnable{
private boolean flag;
DieLock(boolean flag){
this.flag=flag;
}
public void run() {
if(flag) {
while(true) {
synchronized(MyLock.obj1) {
System.out.println(Thread.currentThread().getName()+"....if...obj1...");
synchronized(MyLock.obj2) {
System.out.println(Thread.currentThread().getName()+".....if.....obj2.....");
}
}
}
}
else {
while(true){
synchronized(MyLock.obj2) {
System.out.println(Thread.currentThread().getName()+"....else...obj2...");
synchronized(MyLock.obj1) {
System.out.println(Thread.currentThread().getName()+".....else.....obj1.....");
}
}
}
}
}
}
运行结果:
产生死锁原因:线程0 想要得到obj2 锁进行下面的操作,而obj2锁被线程1 所占有。
线程1想得到obj1锁 进行下面的操作,而obj1锁被线程0 所占有。
二、多生产者与多消费者之间的死锁
public class ManyIOput {
public static void main(String[] args) {
Person person=new Person();
Input in=new Input(person);
Output out=new Output(person);
Thread t0=new Thread(in);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
Thread t3=new Thread(out);
t0.start();
t1.start();
t2.start();
t3.start();
}
}
class Person{
private String name;
private String age;
private boolean redux=false;
private boolean flag=true;
public synchronized void setPerson() {
while(redux) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(flag) {
flag=false;
this.name="wppppppppppppppppp";
this.age="18";
}
else {
flag=true;
this.name="余周周";
this.age="16";
}
redux=true;
this.notify();
}
public synchronized void getPerson(){
while(!redux) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(name+"--------+-------"+age);
redux=false;
this.notify();
}
}
class Input implements Runnable{
private boolean flag=true;
private Person person;
Input(Person person){
this.person=person;
}
public void run() {
while(true){
person.setPerson();
}
}
}
class Output implements Runnable{
private Person person;
Output(Person person){
this.person=person;
}
public void run() {
while(true) {
person.getPerson();
}
}
}
运行结果为:
产生死锁的原因:
当生产者t0 等待时,notify唤醒了其它三线程中的任意一个,假如唤醒了是生产者t1 那么t1 也进入等待,产生死锁。
解决的办法是,将notify改变成notifyAll 使之将全部线程唤醒,进而避免了死锁。