2015-05-12 191 views
0

我有一個類,它啓動所有的線程。如何將元素一次添加到另一個隊列中?

BlockingQueue<MyClass> otherQueue1 = new ArrayBlockingQueue<MyClass>(length); 
BlockingQueue<MyClass> niceQueue = new ArrayBlockingQueue<MyClass>(length); 
service = Executors.newFixedThreadPool(length); 
for (int k = 0; k < length; k++) { 
    service.submit(new MyClass(otherQueue1, id)); 
} 

在這種for循環,我想將這個創建MyClassniceQueue。怎麼做?

回答

0
BlockingQueue<MyClass> otherQueue1 = new ArrayBlockingQueue<MyClass>(length); 
BlockingQueue<MyClass> niceQueue = new ArrayBlockingQueue<MyClass>(length); 
    service=Executors.newFixedThreadPool(length); 
    for(int k=0; k < length; k++){ 
     MyClass myClass = new MyClass(otherQueue1, id); #save reference in local variable 
     niceQueue.add(myClass);       #add saved reference to queue 
     service.submit(myClass);       #submit, same as in your example 
    } 
} 
+0

非常感謝您 – prgst

+0

您能告訴我如何在不執行'queue.take()'的情況下打印隊列中的東西嗎?我需要物體留在原處。 – prgst

相關問題