代码示范
public class ProduceConsume {
private int i = 0;
private final Object LOCK = new Object();
private volatile boolean isProduce = false;
public void produce() {
synchronized (LOCK) {
if (isProduce) {
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
i++;
System.out.println("p-> " + i);
LOCK.notify();
isProduce = true;
}
}
}
public void consume() {
synchronized (LOCK) {
if (isProduce) {
System.out.println("c-> i");
LOCK.notify();
isProduce = false;
} else {
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
ProduceConsume pc = new ProduceConsume();
Stream.of("p1", "p2").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true)
pc.produce();
}
}.start()
);
Stream.of("c1", "c2").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true)
pc.consume();
}
}.start()
);
}
具体过程
1.这里定义了4个线程,两个生产者(p1,p2)两个消费者(c1,c2)
一开始4个线程继续抢占cpu资源,假设cpu资源还是分配给了c1,则c1执行run方法,调用consume()。获得对象锁LOCK,此时isProduce为false,则调用LOCK.wait()线程进入等待,LOCK锁释放。
2.此时c1线程处于等待状态。p1,p2,c2抢占cpu资源,假设cpu资源分配给了c2,则c2执行run方法,调用consume()。获得对象锁LOCK,此时isProduce为false,则调用LOCK.wait()线程进入等待,LOCK锁释放。
3.此时c1,c2线程处于等待状态。p1,p2抢占cpu资源,假设cpu资源分配给了p1,则p1执行run方法,调用produce()。获得对象锁LOCK,此时
isProduce为false,则执行生产任务,然后唤醒c1或c2线程,设置isProduce为true。
4.假设唤醒c1线程,p1,p2,c1抢占cpu资源,此时资源分配还是给了p1,由于isProduce为true,则p1线程进入等待。
5.此时c2,p1线程处于等待状态。c1和p2抢占cpu资源,假设cpu资源分配给了p2,p2是生产任务,因为此时isProduce为true,则进入等待。
6.此时p1,p2,c2线程处于等待状态。cpu资源自然而然的被c1占用,因为此时isProduce为true,则可以唤醒线程,设置isProduce为false。
7.此时等待唤醒的有p1,p2,c2,假设c1线程唤醒了c2线程,由于isProduce为false,那么c1和c2线程都会进入等待(先后顺序不一定)。那么造成的结果就是没有产生死锁,但是4个线程都在等待状态,程序无法正常执行。
以上只是其中的一种可能出现的问题。
解决方法
public class ProduceConsume {
private int i = 0;
private final Object LOCK = new Object();
private volatile boolean isProduce = false;
public void produce() {
synchronized (LOCK) {
while (isProduce) {
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.println("p-> " + i);
LOCK.notifyAll();
isProduce = true;
}
}
public void consume() {
synchronized (LOCK) {
while (!isProduce) {
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("c-> i");
LOCK.notifyAll();
isProduce = false;
}
}
public static void main(String[] args) {
ProduceConsume pc = new ProduceConsume();
Stream.of("p1", "p2").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true)
pc.produce();
}
}.start()
);
Stream.of("c1", "c2").forEach(n ->
new Thread(n) {
@Override
public void run() {
while (true)
pc.consume();
}
}.start()
);
}
}
notify()替换成notifyAll(),唤醒所有等待的线程。while替换了原来的if,是为了进行二次判断,因为被唤醒的线程,保持了原来的执行的地方。会接着记录的位置进行执行。