今天把这个题目练习了一下,但是出现了一些问题,就是如何有效控制产品的产生数量,希望有人给讲解一下!
package com.itpractice;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerAndConsumerDemo2 {
public static void main(String[] args) {
Resource2 res = new Resource2();
Thread t1 = new Thread(new Producer2(res));
Thread t2 = new Thread(new Producer2(res));
Thread t3 = new Thread(new Consumer2(res));
Thread t4 = new Thread(new Consumer2(res));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition con_pro = lock.newCondition();
private Condition con_con = lock.newCondition();
public void setResource(String name) throws InterruptedException {
lock.lock();
try {
while (flag)
con_pro.await();
this.name = name + count++;
System.out.println(Thread.currentThread().getName() + "---生产者---"
+ this.name);
flag = true;
con_con.signal();
} finally {
lock.unlock();
}
}
public void outResource() throws InterruptedException {
lock.lock();
try {
while (!flag)
con_con.await();
System.out.println(Thread.currentThread().getName() + "---消费者---"
+ this.name);
flag = false;
con_pro.signal();
} finally {
lock.unlock();
}
}
}
class Producer2 implements Runnable {
private Resource2 res;
private int x = 0;
Producer2(Resource2 res) {
this.res = res;
}
public void run() {
while (x < 10) {
try {
res.setResource("产品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer2 implements Runnable {
private Resource2 res;
Consumer2(Resource2 res) {
this.res = res;
}
public void run() {
while (true) {
try {
res.outResource();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}