import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 生产者和消费者案例
* @author fanfan
*
*/
public class TestProductorAndConsumer3 {
public static void main(String[] args) {
Clerk2 cle = new Clerk2();
Productor2 pr = new Productor2(cle);
Consumer2 cr = new Consumer2(cle);
new Thread(pr,"生产者A").start();
new Thread(cr,"消费者B").start();
new Thread(pr,"生产者A1").start();
new Thread(cr,"消费者B1").start();
new Thread(pr,"生产者A3").start();
new Thread(cr,"消费者B3").start();
new Thread(pr,"生产者A4").start();
new Thread(cr,"消费者B4").start();
new Thread(pr,"生产者A5").start();
new Thread(cr,"消费者B5").start();
new Thread(pr,"生产者A7").start();
new Thread(cr,"消费者B7").start();
}
}
class Clerk2{
private int product = 0;
//采用同步锁 就不使用synchronize
private Lock lock = new ReentrantLock();
//
private Condition condition = lock.newCondition();
//进货
public void get() throws InterruptedException{
lock.lock();
try {
while(product>=1){ //为了避免虚假唤醒问题,应该总是使用在循环中
System.out.println("产品已满");
try {
condition.await();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
System.out.println(Thread.currentThread().getName()+":"+ ++product);
condition.signalAll();
} finally {
// TODO: handle finally clause
lock.unlock();
}
}
//卖货
public void sale() throws InterruptedException{
lock.lock();
try {
while(product <=0){
System.out.println("缺货");
try {
condition.await();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
System.out.println(Thread.currentThread().getName()+":"+ --product);
condition.signalAll();
} finally {
// TODO: handle finally clause
lock.unlock();
}
}
}
//生产者
class Productor2 implements Runnable{
private Clerk2 clerk;
public Productor2(Clerk2 clerk){
this.clerk = clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0;i<20;i++){
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
clerk.sale();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//消费者
class Consumer2 implements Runnable{
private Clerk2 clerk;
public Consumer2(Clerk2 clerk){
this.clerk = clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i = 0;i<20;i++){
try {
clerk.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
线程(三)
猜你喜欢
转载自blog.csdn.net/qq_30443907/article/details/84710799
今日推荐
周排行