生活随笔
收集整理的這篇文章主要介紹了
java中的生产者消费者模式详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
方式 一: Synchronized方式
注:此種方式會造成資源的浪費:
利用鎖的notifyAll()方法會將所有的線程都喚醒,會造成資源的浪費
class Resource {private String name
;private int count
= 1;private boolean flag
= false;public synchronized void set(String name
) {while (flag
) { try {this.wait();} catch (Exception e
) {}}this.name
= name
+ "--" + count
++;System
.out
.println(Thread
.currentThread().getName() + "...Producer..." + this.name
);this.flag
= true;this.notifyAll();}public synchronized void out() {while (!flag
) {try {this.wait();} catch (Exception e
) {}}System
.out
.println(Thread
.currentThread().getName() + ".....Consumer....." + this.name
);this.flag
= false;this.notifyAll();}
}class Producer implements Runnable {private Resource r
;public Producer(Resource r
) {this.r
= r
;}public void run() {while (true) {r
.set("+Items+");}}
}class Consumer implements Runnable {private Resource r
;public Consumer(Resource r
) {this.r
= r
;}public void run() {while (true) {r
.out();}}
}public class ProducerAndConsumer {public static void main(String
[] args
) {Resource r
= new Resource();new Thread(new Producer(r
)).start();new Thread(new Producer(r
)).start();new Thread(new Consumer(r
)).start();new Thread(new Consumer(r
)).start();}
}
方式二:
利用Lock的方式顯示的聲明鎖
這種方式可以人喚醒想要喚醒的線程,能夠減少資源的浪費
import java
.util
.concurrent
.locks
.*
;class Resource {private String name
;private int count
= 1;private boolean flag
= false;private Lock lock
= new ReentrantLock();private Condition condition
= lock
.newCondition();private Condition conditionPro
= lock
.newCondition();public void set(String name
) throws InterruptedException
{lock
.lock();try {while (flag
)condition
.await();this.name
= name
+ "--" + count
++;System
.out
.println(Thread
.currentThread().getName() + "...Producer..." + this.name
);this.flag
= true;conditionPro
.signal();} finally {lock
.unlock(); }}public void out() throws InterruptedException
{lock
.lock();try {while (!flag
)conditionPro
.await();System
.out
.println(Thread
.currentThread().getName() + ".....Consumer....." + this.name
);this.flag
= false;condition
.signal();} finally {lock
.unlock();}}
}class Producer implements Runnable {private Resource r
;public Producer(Resource r
) {this.r
= r
;}public void run() {while (true) {try {r
.set("+Items+");} catch (InterruptedException e
) {}}}
}class Consumer implements Runnable {private Resource r
;public Consumer(Resource r
) {this.r
= r
;}public void run() {while (true) {try {r
.out();} catch (InterruptedException e
) {}}}
}public class ProducerAndConsumer {public static void main(String
[] args
) {Resource r
= new Resource();new Thread(new Producer(r
)).start();new Thread(new Producer(r
)).start();new Thread(new Consumer(r
)).start();new Thread(new Consumer(r
)).start();}
}
總結
以上是生活随笔為你收集整理的java中的生产者消费者模式详解的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。