多線程協作下的生產者與消費者(基於synchronized和ReentLock)

<code>package test.lock;

import java.util.Stack;

public class ConAndProService_Synchronized {
private final static Stack<integer> container = new Stack<>(); //生產東西的容器
private final static Object lock = new Object();//全局鎖 多個線程共享
private final static Integer threshold = 4;//閾值

public void producer() {
while(true){
synchronized (lock){
try {
while (container.size() == threshold) { //當生產的數量等於閾值 當前線程讓出cpu資源 等待被喚醒 喚醒時進行cpu上下文切換
lock.wait();
}
int val = 1;
System.out.println("生產者: ThreadName : " + Thread.currentThread().getName() + " ...........producer val ........ = " + val);
container.add(val);
lock.notifyAll(); //喚醒所有在監視器lock上等待的線程
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

public void consumer() {
while(true){
synchronized (lock){
try {
while (container.size() == 0) {// 沒有物品消費時,線程wait
lock.wait();
}
int val = container.pop();
System.out.println("消費者: ThreadName : " + Thread.currentThread().getName() + "*************** consumer val *************** = " + val);
lock.notifyAll();//
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {

new Thread(()->{
new ConAndProService_Synchronized().producer();
}).start();


for(int i=0;i<2;i++){
new Thread(()->{
new ConAndProService_Synchronized().consumer();
}).start();
}



}


}/<integer>/<code>
<code>package test.lock;

import java.util.Stack;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConAndProService_ReentLock {
private final static Stack<integer> container = new Stack<>();
private final static ReentrantLock lock = new ReentrantLock();
private final static Condition condition = lock.newCondition();
private final static Integer threshold = 4;

public void producer() {
while(true){
try {
lock.lock();
while (container.size() == threshold) {
condition.await();
}
int val = 1;
System.out.println("ThreadName : " + Thread.currentThread().getName() + " ...........producer val ........ = " + val);
container.add(val);
condition.signalAll();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

public void consumer() {
while(true){
try {
lock.lock();
while (container.size() == 0) {//注3
condition.await();
}
int val = container.pop();
System.out.println("ThreadName : " + Thread.currentThread().getName() + "*************** consumer val *************** = " + val);
condition.signalAll();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

public static void main(String[] args) {

new Thread(()->{
new ConAndProService_ReentLock().producer();
}).start();

new Thread(()->{
new ConAndProService_ReentLock().producer();
}).start();

new Thread(()->{
new ConAndProService_ReentLock().consumer();
}).start();

}


}/<integer>/<code>


分享到:


相關文章: