定義一個(gè)ReentrantLock鎖,同時(shí)new出兩個(gè)condition,一個(gè)控制隊(duì)滿,一個(gè)
控制隊(duì)空
//生產(chǎn)者 消費(fèi)者
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.*;
import java.util.Random;
class Producer implements Runnable{
public static Random random = new Random(7777);
public ReentrantLock lock;
public Condition full;
public Condition empty;
public Queue<Integer> queue;
public int maxSize;
Producer(ReentrantLock lock, Condition full,Condition empty, Queue<Integer> queue, int maxSize){
this.lock = lock; this.queue = queue;
this.full = full; this.empty = empty;
this.maxSize = maxSize;
}
public void run() {
try{
while(true) {
lock.lock();
while(queue.size() == maxSize) full.await();
int number = random.nextInt(100);
queue.offer(number);
System.out.println(Thread.currentThread().toString() + "produce: " + String.valueOf(number));
empty.signalAll();
lock.unlock();
Thread.sleep(3000);
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
ReentrantLock lock;
Condition full;
Condition empty;
Queue<Integer> queue;
public Consumer(ReentrantLock lock, Condition full, Condition empty, Queue<Integer> queue) {
this.lock = lock; this.full = full;
this.empty = empty; this.queue = queue;
}
public void run() {
try{
while(true) {
lock.lock();
while(queue.size() == 0) empty.await();
int number = queue.poll();
System.out.println(Thread.currentThread().toString() + "Consumer: " + String.valueOf(number));
full.signalAll();
lock.unlock();
Thread.sleep(2000);
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
public class Main{
public static void main(String []args) {
ReentrantLock lock = new ReentrantLock();
Condition proCondition = lock.newCondition();
Condition conCondition = lock.newCondition();
LinkedList<Integer> queue = new LinkedList<>();
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(new Producer(lock, conCondition, proCondition, queue, 10));
executor.submit(new Producer(lock, conCondition, proCondition, queue, 10));
executor.submit(new Consumer(lock, conCondition, proCondition, queue));
executor.submit(new Consumer(lock, conCondition, proCondition, queue));
try{
Thread.sleep(60000);
}catch(Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}
本站文章版權(quán)歸原作者及原出處所有 。內(nèi)容為作者個(gè)人觀點(diǎn), 并不代表本站贊同其觀點(diǎn)和對(duì)其真實(shí)性負(fù)責(zé),本站只提供參考并不構(gòu)成任何投資及應(yīng)用建議。本站是一個(gè)個(gè)人學(xué)習(xí)交流的平臺(tái),網(wǎng)站上部分文章為轉(zhuǎn)載,并不用于任何商業(yè)目的,我們已經(jīng)盡可能的對(duì)作者和來(lái)源進(jìn)行了通告,但是能力有限或疏忽,造成漏登,請(qǐng)及時(shí)聯(lián)系我們,我們將根據(jù)著作權(quán)人的要求,立即更正或者刪除有關(guān)內(nèi)容。本站擁有對(duì)此聲明的最終解釋權(quán)。