public class Producer extends Thread {
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
ScheduledExecutorService executor = Executors
.newScheduledThreadPool(12);
int initialDelay = 5;
int pollingFrequency = 5;
Producer producer = new Producer();
@SuppressWarnings({ "rawtypes", "unused" })
ScheduledFuture schedFutureProducer = executor.scheduleWithFixedDelay(
producer, initialDelay, pollingFrequency, TimeUnit.SECONDS);
for (int i = 0; i < 3; i++) {
Consumer consumer = new Consumer();
@SuppressWarnings({ "rawtypes", "unused" })
ScheduledFuture schedFutureConsumer = executor
.scheduleWithFixedDelay(consumer, initialDelay,
pollingFrequency, TimeUnit.SECONDS);
}
}
@Override
public void run() {
list.add("object added to list is " + System.currentTimeMillis());
///adding in list become slow also because of synchronized behavior
}
}
class Consumer extends Thread {
@Override
public void run() {
getObjectFromList();
}
private void getObjectFromList() {
synchronized (Producer.list) {
if (Producer.list.size() > 0) {
System.out.println("Object name removed by "
+ Thread.currentThread().getName() + "is "
+ Producer.list.get(0));
Producer.list.remove(Producer.list.get(0));
}
}
}
}
只是爲了澄清:'ExecutorService'只是一個接口。你可以在一個線程中執行'ExecutorService'類,它只要運行一個可運行的類就可以運行每個可運行的類(我相信'java.util.concurrent'包中有一個實現就是這麼做的) 。但在實踐中*,大多數ExecutorService實現是完整的生產者 - 消費者實現。 –
你是絕對正確的,通過'ExecutorService''我的意思是「*執行'ExecutorService' *」的'Executors.newFixedThreadPool()'返回的東西。感謝您的澄清。 –
謝謝你們。所以,如果我創建使用的newFixedThreadPool(8),然後就可以執行大約1000可運行任務的執行服務,請確認一下我的情況的理解: 1.最多8個線程將在處理開始創建 2 ,而8個線程正忙,992個任務將被保存在內部隊列中 3.另外,因爲它是一個無界隊列,所以我可以提交給執行程序服務的任務數量沒有上限。 如果我使用有界隊列創建ExecutorService,上述場景會產生什麼影響?它會表現更好嗎? 謝謝,O. – Oxford