问题如下:
1)若消费者先抢到CPU执行权,会先消费资源;但若此时没有资源 ,应当先生产再消费;
2)若生产者先抢到CPU执行权,会先生产资源;但若此时有资源,应当先消费再生产;
解决思路:
1)对生产者而言,先查看是否有资源,有就等待,无就等待消费者消费完之后,通知生产
2)对消费者而言,先查看是否有资源,有就消费,无就等待生产者生产完之后,通知消费
Java代码实现:synchronized+wait/notifyAll
public class ProductConsumer {
private static int res = 10; // 资源
static Object objLock = new Object();// 同步锁对象
static boolean haveRes = false;// 标志位,是否有资源
public static void main(String[] args) {
Thread product = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (objLock) {
if (haveRes) {
try {
objLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
res--;
if (res > 0)
System.out.println(res);
haveRes = !haveRes;
objLock.notify();
}
}
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
synchronized (objLock) {
if (!haveRes) {
try {
objLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
res--;
if (res > 0)
System.out.println(res);
haveRes = !haveRes;
objLock.notify();
}
}
}
});
product.start();
consumer.start();
}
}
代码输出:
9
8
7
6
5
4
3
2
1
private static Object obj = new Object();// 同步锁
private static boolean ishave = false;// 判断条件
public static class Producer implements Runnable {
@Override
public void run() {
synchronized (obj) {
// 有就等待
while (ishave) {
System.out.println("It is full!");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 没有就生产,并通知消费者
System.out.println("I am producing!");
ishave = true;
obj.notify();
}
}
}
public static class Consumer implements Runnable {
@Override
public void run() {
synchronized (obj) {
// 没有就等待
while (!ishave) {
System.out.println("It is empty!");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 有就消费,并通知生产者
System.out.println("I am consuming!");
ishave = false;
obj.notify();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Producer());
Thread t2 = new Thread(new Consumer());
Thread t3 = new Thread(new Producer());
Thread t4 = new Thread(new Consumer());
t1.start();
t2.start();
t3.start();
t4.start();
}
输出:
I am producing!
I am consuming!
I am producing!
I am consuming!