package com.qey.interview;
import javax.validation.constraints.Max;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @ClassName ProductCustomer
* @Description
* @Author qianxl
* @Date 2020-06-29 20:39
* @Version 1.1
**/
public class ProductCustomer {
// private ReentrantLock reentrantLock = new ReentrantLock();
private Lock lock = new ReentrantLock();
//创建两个条件变量,一个为缓冲区非满,一个为缓冲区非空
private final Condition notNull = lock.newCondition(); //lock
private final Condition notEmpty = lock.newCondition();
private static Integer count = 0;//设置生产者标记
private static final Integer MAXCOUNT = 10; //设置生产者最大的值
class Product implements Runnable {
@Override
public void run() {
for(int i=0;i<MAXCOUNT;i++){
lock.lock();
try {
while (count == 100) {
notNull.await();
}
count++;
System.out.println(Thread.currentThread().getName() + "count's value++" + count);
notEmpty.signal();; //LockSupport.unpark(node.thread); 底层调用unpark 进行解锁
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
class Customer implements Runnable {
@Override
public void run() {
for(int i=0;i<MAXCOUNT;i++) {
lock.lock();
try {
while (count == 0) {
notEmpty.await();
}
count--;
System.out.println(Thread.currentThread().getName() + "count's value--" + count);
notNull.signal();
// Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy());
ThreadPoolExecutor threadPoolExecutor2 = new ThreadPoolExecutor(3, 5, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.DiscardOldestPolicy());
Product product = new ProductCustomer().new Product();
Customer customer = new ProductCustomer().new Customer();
// new Thread(customer).start();
new Thread(product).start();
new Thread(customer).start();
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// new Thread(product).start();
// new Thread(customer).start();
// threadPoolExecutor.execute(customer);
// threadPoolExecutor.execute(product);
// threadPoolExecutor.execute(product);
// threadPoolExecutor.execute(customer);
// for (int i = 0; i < 5; i++) {
// threadPoolExecutor.execute(customer);
//
// }
// for (int i = 0; i < 5; i++) {
// threadPoolExecutor2.execute(product);
// }
}
}
reentranklock简单实现生产者和消费者模型
最新推荐文章于 2022-03-30 23:04:12 发布