[英]Thread Execution in Java
問題陳述:有n個線程,n/2個線程是生產者,n/2個是消費者,生產者1線程產生的數字必須被消費者1線程消耗。 線程也必須按順序運行,生產者 1,然后是消費者 1,又是生產者 2,然后是消費者 2……依此類推……
我正在使用線程在java中實現生產者消費者,但要求是有N/2個生產者線程和N/2個消費者線程,N個消費者線程應該消耗由N個生產者產生的值,n-1個消費者線程應該由n-1個生產者消耗價值。
我已經使用阻塞隊列實現了這個,但沒有得到想要的輸出:
package paytm;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerWithBlockingQueue {
public static class Producer implements Runnable {
private BlockingQueue<Integer> queue;
private int next = 0;
private String thereadName;
public Producer(BlockingQueue<Integer> queue,String threadName) {
this.queue = queue;
this.thereadName = threadName;
}
@Override
public void run() {
while (true) {
try {
if(next<10) {
queue.put(next);
System.out.println(thereadName+ " "+ next);
}
} catch (InterruptedException e) {
}
next++;
}
}
}
public static class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
private String thereadName;
public Consumer(BlockingQueue<Integer> queue,String threadName) {
this.queue = queue;
this.thereadName = threadName;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
Integer next;
try {
next = queue.take();
System.out.println(thereadName+ " "+ next);
} catch (InterruptedException e) {
}
}
}
}
}
public static void main(String args[]) throws Exception {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(1);
Thread producer1 = new Thread(new Producer(queue,"producer1"));
Thread producer2 = new Thread(new Producer(queue,"producer2"));
Thread consumer1 = new Thread(new Consumer(queue,"Consumer1"));
Thread consumer2 = new Thread(new Consumer(queue,"Consumer2"));
producer1.start();
producer2.start();
consumer1.start();
consumer2.start();
// producer1.join();
// producer2.join();
// consumer1.join();
// consumer2.join();
}
}
// Output :
producer1 0
consumer1 0
producer2 1
consumer2 1
producer3 2
consumer3 2 so on...
這可能不會做你期望它做的事情:
while (true)
synchronized(queue) {
...
}
}
假設consumer1
贏得比賽並進入synchronized
塊,而consumer2
被迫等待。 當consumer1
做它的事情,然后從synchronized
塊中退出時,你認為會發生什么?
Java 語言規范沒有說明在這種情況下必須發生什么,但在大多數實現中,實際會發生的是, consumer1
將在consumer2
開始喚醒之前立即返回synchronized
塊。
Java 中的內在鎖是不公平的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.