import java.util.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
var q = new TaskQueue();
var ts = new ArrayList<Thread>();
for (int i = 0; i < 5; i++) {
final String thNo = "Thread_" + Integer.toString(i + 1);
var t = new Thread(
() -> {
// 执行task:
while (true) {
try {
Thread.sleep(200);
String s = q.getTask(thNo);
System.out.println(thNo + " executing task: " + s);
Thread.sleep(200 + (int) (Math.random() * 400));
System.out.println(thNo + " executed task: " + s);
} catch (InterruptedException e) {
return;
}
});
t.start();
ts.add(t);
var add = new Thread(() -> {
for (int i = 0; i < 10; i++) {
// 放入task:
// String s = "t-" + Math.random();
System.out.println("adding task: " + i);
q.addTask(Integer.toString(i));
System.out.println("added task: " + i);
Thread.sleep(100);
add.start();
add.join();
System.out.println("waiting for all tasks to complete!");
Thread.sleep(1000);
for (var t : ts) {
t.interrupt();
class TaskQueue {
Queue<String> queue = new LinkedList<>();
public synchronized void addTask(String s) {
this.queue.add(s);
// this.notifyAll();
this.notify();
public synchronized String getTask(String tName) throws InterruptedException {
while (queue.isEmpty()) {
System.out.println(tName + " waiting...");
this.wait();
System.out.println(tName + " awake.");
System.out.println(tName + " getting task " + queue.element());
return queue.remove();
Sign in to make a reply
Junes_99994
import java.util.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
var q = new TaskQueue();
var ts = new ArrayList<Thread>();
for (int i = 0; i < 5; i++) {
final String thNo = "Thread_" + Integer.toString(i + 1);
var t = new Thread(
() -> {
// 执行task:
while (true) {
try {
Thread.sleep(200);
String s = q.getTask(thNo);
System.out.println(thNo + " executing task: " + s);
Thread.sleep(200 + (int) (Math.random() * 400));
System.out.println(thNo + " executed task: " + s);
} catch (InterruptedException e) {
return;
}
}
});
t.start();
ts.add(t);
}
var add = new Thread(() -> {
for (int i = 0; i < 10; i++) {
// 放入task:
// String s = "t-" + Math.random();
System.out.println("adding task: " + i);
q.addTask(Integer.toString(i));
System.out.println("added task: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
});
add.start();
add.join();
System.out.println("waiting for all tasks to complete!");
Thread.sleep(1000);
for (var t : ts) {
t.interrupt();
}
}
}
class TaskQueue {
Queue<String> queue = new LinkedList<>();
public synchronized void addTask(String s) {
this.queue.add(s);
// this.notifyAll();
this.notify();
}
public synchronized String getTask(String tName) throws InterruptedException {
while (queue.isEmpty()) {
System.out.println(tName + " waiting...");
this.wait();
System.out.println(tName + " awake.");
}
System.out.println(tName + " getting task " + queue.element());
return queue.remove();
}
}