1、生产者消费者程序执行流
2、常见问题1:无限等待
原因:如上图所示,第一次(i=0)消费者执行完了一次函数,那次函数else语句后面没有执行,因此消费者少执行一次
解决办法:去掉else
错误代码:
public class Test1{
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer pro = new Producer(clerk);
Consumer cus = new Consumer(clerk);
new Thread(pro, "生产者A").start();
new Thread(cus, "消费者B").start();
}
}
//仓库类
class Clerk {
private int product = 0;
//进货
public synchronized void get() {
if (product >= 1) {
System.out.println("仓库已满");
try {
//在仓库已满时才进行等待
this.wait();
} catch (InterruptedException e) {
}
}else {
System.out.println(Thread.currentThread().getName() + ":" + ++product);
//当仓库内存在货物时,通知线程可以进行卖货了
this.notifyAll();
}
}
//卖货
public synchronized void sale() {
if (product <= 0) {
System.out.println("缺货");
try {
//在仓库缺货时才进行等待
this.wait();
} catch (InterruptedException e) {
}
}else {
System.out.println(Thread.currentThread().getName() + ":" + --product);
//通知线程可以进行进货了,存在空位
this.notifyAll();
}
}
}
//生产者类
class Producer implements Runnable {
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.get();
}
}
}
//消费者类
class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
3、虚假唤醒
即:出现-1的情况
虚假唤醒:
假设A、B、C、D中,AB为生产者、CD为消费者;当产品数量为0时,C先进去锁,然后wait;此时,D也进去锁,wait;然后A进去,生产了一个产品,在唤醒其他线程;B会执行之后的–方法执行完毕,D在执行一次–方法,变成-1;
原因:
if完了,会执行后边的语句;
解决方法:
if条件换成while判断
错误代码:
public class Test1{
public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer pro = new Producer(clerk);
Consumer cus = new Consumer(clerk);
new Thread(pro, "生产者A").start();
new Thread(cus, "消费者B").start();
new Thread(pro, "生产者C").start();
new Thread(cus, "消费者D").start();
}
}
//仓库类
class Clerk {
private int product = 0;
//进货
public synchronized void get() {
if (product >= 1) {
System.out.println("仓库已满");
try {
//在仓库已满时才进行等待
this.wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + ":" + ++product);
//当仓库内存在货物时,通知线程可以进行卖货了
this.notifyAll();
}
//卖货
public synchronized void sale() {
if (product <= 0) {
System.out.println("缺货");
try {
//在仓库缺货时才进行等待
this.wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + ":" + --product);
//通知线程可以进行进货了,存在空位
this.notifyAll();
}
}
//生产者类
class Producer implements Runnable {
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.get();
}
}
}
//消费者类
class Consumer implements Runnable {
private Clerk clerk;
public Consumer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}