import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ProductConsumer {
/**
* 需求:通过lock实现生产者消费者多线程同步
思路:创建生成和消费方法,在要同步的代码前用lock对象锁住
* 判断过产品是否为空,为空则生产,否则不生产,唤醒消费者消费,并 解锁,同理消费方法也是先加锁,判断的是否有产品,有则消费,没有则
* 唤醒生产者生产,然后解锁.
*
*
*/
private ProductConsumer p;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void product() {
lock.lock();
try {
while (flag)
try {
condition_pro.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "生成产品->"
+ count++);
flag = true;
condition_con.signal();
} finally {
lock.unlock();
}
}
public void consumer() {
try {
lock.lock();
while (!flag)
try {
condition_con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "消费产品->"
+ this.count);
flag = false;
condition_pro.signal();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
new Thread(new ProductConsumer().new Product(new ProductConsumer()))
.start();
new Thread(new ProductConsumer().new Consumer(new ProductConsumer()))
.start();
new Thread(new ProductConsumer().new Product(new ProductConsumer()))
.start();
new Thread(new ProductConsumer().new Consumer(new ProductConsumer()))
.start();
}
class Product implements Runnable {
Product(ProductConsumer pro) {
p = pro;
}
@Override
public void run() {
product();
}
}
class Consumer implements Runnable {
Consumer(ProductConsumer con) {
p = con;
}
@Override
public void run() {
consumer();
}
}
}
如题:为什么我调用了 consumer()方法却没有输出,而且生产者的输出也不对呢,求解。。。。。谢谢
|