[英]producer - consumer multithreading in Java
我想在Java中使用多線程等待和通知方法編寫程序。
該程序有一個堆棧(max-length = 5)。 生產者永遠生成數字並將其放入堆棧中,消費者從堆棧中選擇它。
當堆棧已滿時,生產者必須等待,當堆棧為空時,消費者必須等待。
問題是它只運行一次,我的意思是一旦它產生5個數字就會停止,但是我將run方法放入while(true)塊以運行不間斷但不會。
這是我到目前為止所嘗試的。
制片人類:
package trail;
import java.util.Random;
import java.util.Stack;
public class Thread1 implements Runnable {
int result;
Random rand = new Random();
Stack<Integer> A = new Stack<>();
public Thread1(Stack<Integer> A) {
this.A = A;
}
public synchronized void produce()
{
while (A.size() >= 5) {
System.out.println("List is Full");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
result = rand.nextInt(10);
System.out.println(result + " produced ");
A.push(result);
System.out.println(A);
this.notify();
}
@Override
public void run() {
System.out.println("Producer get started");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
produce();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
和消費者:
package trail;
import java.util.Stack;
public class Thread2 implements Runnable {
Stack<Integer> A = new Stack<>();
public Thread2(Stack<Integer> A) {
this.A = A;
}
public synchronized void consume() {
while (A.isEmpty()) {
System.err.println("List is empty" + A + A.size());
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println(A.pop() + " Consumed " + A);
this.notify();
}
@Override
public void run() {
System.out.println("New consumer get started");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
consume();
}
}
}
這是主要方法:
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
Thread1 thread1 = new Thread1(stack);// p
Thread2 thread2 = new Thread2(stack);// c
Thread A = new Thread(thread1);
Thread B = new Thread(thread2);
Thread C = new Thread(thread2);
A.start();
B.start();
C.start();
}
您應該在堆棧上進行同步而不是將其放在方法級別嘗試此代碼。
也不要在你的線程類中初始化堆棧,無論你是在主類的構造函數中傳遞它們,所以不需要那樣做。
總是盡量避免使用synchronized關鍵字標記任何方法而不是嘗試將關鍵的代碼段放在synchronized塊中,因為同步區域的大小越大,它將對性能產生影響。
因此,始終只將該代碼放入需要線程安全的同步塊中。
制片人代碼:
public void produce() {
synchronized (A) {
while (A.size() >= 5) {
System.out.println("List is Full");
try {
A.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
result = rand.nextInt(10);
System.out.println(result + " produced ");
A.push(result);
System.out.println("stack ---"+A);
A.notifyAll();
}
}
消費者代碼:
public void consume() {
synchronized (A) {
while (A.isEmpty()) {
System.err.println("List is empty" + A + A.size());
try {
System.err.println("wait");
A.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println(A.pop() + " Consumed " + A);
A.notifyAll();
}
}
您的使用者和您的生產者在不同的對象上同步,並且不會相互阻塞。 如果這樣可行,我敢說這是偶然的。
閱讀java.util.concurrent.BlockingQueue
和java.util.concurrent.ArrayBlockingQueue
。 這些為您提供了更現代,更簡單的方式來實現此模式。
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
我認為如果你試圖分離目前混合的三件事情,那么理解和處理同步會更好:
將要完成實際工作的任務。 對於類名稱Thread1
和Thread2
是誤導性的。 它們不是Thread對象,但它們實際上是實現您為Thread
對象提供的Runnable接口的作業或任務。
您在main中創建的線程對象本身
共享對象,它封裝了隊列,堆棧等上的同步操作/邏輯。此對象將在任務之間共享。 在這個共享對象中,您將負責添加/刪除操作(使用synchronized塊或同步方法)。 當前(正如已經指出的那樣),同步是在任務本身上完成的(即每個任務等待並通知其自身鎖定並且沒有任何反應)。 當你分開關注點,即讓一個班級做一件事情時,最終會清楚問題出在哪里。
試試這個:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CircularArrayQueue<T> {
private volatile Lock rwLock = new ReentrantLock();
private volatile Condition emptyCond = rwLock.newCondition();
private volatile Condition fullCond = rwLock.newCondition();
private final int size;
private final Object[] buffer;
private volatile int front;
private volatile int rare;
/**
* @param size
*/
public CircularArrayQueue(int size) {
this.size = size;
this.buffer = new Object[size];
this.front = -1;
this.rare = -1;
}
public boolean isEmpty(){
return front == -1;
}
public boolean isFull(){
return (front == 0 && rare == size-1) || (front == rare + 1);
}
public void enqueue(T item){
try {
// get a write lock
rwLock.lock();
// if the Q is full, wait the write lock
if(isFull())
fullCond.await();
if(rare == -1){
rare = 0;
front = 0;
} else if(rare == size - 1){
rare = 0;
} else {
rare ++;
}
buffer[rare] = item;
//System.out.println("Added\t: " + item);
// notify the reader
emptyCond.signal();
} catch(InterruptedException e){
e.printStackTrace();
} finally {
// unlock the write lock
rwLock.unlock();
}
}
public T dequeue(){
T item = null;
try{
// get the read lock
rwLock.lock();
// if the Q is empty, wait the read lock
if(isEmpty())
emptyCond.await();
item = (T)buffer[front];
//System.out.println("Deleted\t: " + item);
if(front == rare){
front = rare = -1;
} else if(front == size - 1){
front = 0;
} else {
front ++;
}
// notify the writer
fullCond.signal();
} catch (InterruptedException e){
e.printStackTrace();
} finally{
// unlock read lock
rwLock.unlock();
}
return item;
}
}
您可以使用Java的awesome java.util.concurrent
包及其類。
您可以使用
BlockingQueue
輕松實現生產者消費者問題。BlockingQueue
已經支持在檢索元素時等待隊列變為非空的操作,並且在存儲元素時等待隊列中的空間可用。如果沒有
BlockingQueue
,每次我們將數據放入生產者端的隊列時,我們需要檢查隊列是否已滿,如果已滿,請等待一段時間,再次檢查並繼續。 同樣在消費者方面,我們必須檢查隊列是否為空,如果為空,則等待一段時間,再次檢查並繼續。 但是對於BlockingQueue
我們不必編寫任何額外的邏輯,只需添加Producer中的數據並從Consumer中輪詢數據。
閱讀更多來自:
http://javawithswaranga.blogspot.in/2012/05/solving-producer-consumer-problem-in.html
http://www.javajee.com/producer-consumer-problem-in-java-using-blockingqueue
使用BlockingQueue,LinkedBlockingQueue這非常簡單。 http://developer.android.com/reference/java/util/concurrent/BlockingQueue.html
package javaapplication;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumer {
public static Object lock = new Object();
public static Stack stack = new Stack();
public static void main(String[] args) {
Thread producer = new Thread(new Runnable() {
int i = 0;
@Override
public void run() {
do {
synchronized (lock) {
while (stack.size() >= 5) {
try {
lock.wait();
} catch (InterruptedException e) {
}
}
stack.push(++i);
if (stack.size() >= 5) {
System.out.println("Released lock by producer");
lock.notify();
}
}
} while (true);
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
do {
synchronized (lock) {
while (stack.empty()) {
try {
lock.wait();
} catch (InterruptedException ex) {
Logger.getLogger(ProdCons1.class.getName()).log(Level.SEVERE, null, ex);
}
}
while(!stack.isEmpty()){
System.out.println("stack : " + stack.pop());
}
lock.notifyAll();
}
} while (true);
}
});
producer.start();
consumer.start();
}
}
看看這個代碼示例:
import java.util.concurrent.*;
import java.util.Random;
public class ProducerConsumerMulti {
public static void main(String args[]){
BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>();
Thread prodThread = new Thread(new Producer(sharedQueue,1));
Thread consThread1 = new Thread(new Consumer(sharedQueue,1));
Thread consThread2 = new Thread(new Consumer(sharedQueue,2));
prodThread.start();
consThread1.start();
consThread2.start();
}
}
class Producer implements Runnable {
private final BlockingQueue<Integer> sharedQueue;
private int threadNo;
private Random rng;
public Producer(BlockingQueue<Integer> sharedQueue,int threadNo) {
this.threadNo = threadNo;
this.sharedQueue = sharedQueue;
this.rng = new Random();
}
@Override
public void run() {
while(true){
try {
int number = rng.nextInt(100);
System.out.println("Produced:" + number + ":by thread:"+ threadNo);
sharedQueue.put(number);
Thread.sleep(100);
} catch (Exception err) {
err.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private final BlockingQueue<Integer> sharedQueue;
private int threadNo;
public Consumer (BlockingQueue<Integer> sharedQueue,int threadNo) {
this.sharedQueue = sharedQueue;
this.threadNo = threadNo;
}
@Override
public void run() {
while(true){
try {
int num = sharedQueue.take();
System.out.println("Consumed: "+ num + ":by thread:"+threadNo);
Thread.sleep(100);
} catch (Exception err) {
err.printStackTrace();
}
}
}
}
筆記:
Producer
和兩個Consumers
Producer
將在無限循環中產生0到100之間的隨機數 Consumer
將在無限循環中消耗這些數字 Producer
和Consumer
共享鎖定免費和線程安全LinkedBlockingQueue是線程安全的。 如果使用這些高級並發結構,則可以刪除wait()和notify()方法。 好像你跳過了關於wait()
, notify()
和synchronized
。 看到這個例子 ,它應該對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.