Zrobiłem w ten sposób:
Wątki pobierają elementy (Stringi) z kolejki za pomocą take() w pętli while. While działa dopóki pobrany element jest różny od "end".
Ale mam problem z shutdown() obiektu ExecutorService. Wywołując ją i tak nie kończę wątku, który oczekuje od pustej już kolejki następnych elementów.
Natomiast shutdownNow() wyrzuca:
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(Unknown Source)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(Unknown Source)
at java.util.concurrent.LinkedBlockingQueue.take(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
EDIT:
Klasa main:
public class Main {
private static ExecutorService exe;
public static void main(String[] args) {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();
exe = Executors.newFixedThreadPool(2);
for (int i = 0; i < 100; i++) {
queue.add("word"+i);
}
queue.add("end");
MyThread myth1 = new MyThread(1, queue);
MyThread myth2 = new MyThread(2, queue);
exe.execute(myth1);
exe.execute(myth2);
}
public static void metoda() {
try {
exe.shutdown();
exe.awaitTermination(5, TimeUnit.SECONDS);
exe.shutdownNow();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
metoda run wątku:
public void run() {
int count = 0;
String word = "";
try {
while (!(word = queue.take()).equals("end")) {
word += "#"+rand.nextInt(10000);
System.out.println("Thread "+id+": "+word);
count++;
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("### Elements in queue: "+queue.size()+".\n" +
"### Thread "+id+" process "+count+" elements.");
Main.metoda();
}