【笔记】-线程协调-程序运行笔记
Topic sourceimport java.util.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
//新建TaskQueue实例对象
var q = new TaskQueue();
//存放线程的数组
var ts = new ArrayList<Thread>();
//开启并运行5个线程,每个线程都尝试打印q中的task
for (int i = 0; i < 5; i++) {
var t = new Thread() {
public void run() {
// 执行task:
while (true) {
try {
String s = q.getTask();
//System.out.println("execute task: " + s);
System.out.println(this.getName() + " execute task: " + s + "\n");
} catch (InterruptedException e) {
return;
}
}
}
};
t.start();
ts.add(t);
}
//新建add线程,在线程中,每隔100ms,往q中添加一个String
var add = new Thread(() -> {
for (int i=0; i<10; i++) {
// 放入task:
String s = "t-" + Math.random();
System.out.println("add task: " + s);
q.addTask(s);
//这里每次往q中添加一个String后暂停100ms的原因是为了让上述5个线程中的某一个能够及时捕捉到,并打印
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
}
}
);
//开始执行add线程,并等待add执行完毕
// 这里是main线程等待add线程执行完毕,但是for循环创建的5个线程是在一直运行中的
add.start();
add.join();
//主线程暂停100ms
// 目的是留出一点时间,让上述5个线程能够将q中的String全部get出来
// 然后再对所有的 提出中断请求
Thread.sleep(100);
for (var t : ts) {
t.interrupt();
}
System.out.println("main Thread ended");
}
}
class TaskQueue {
Queue<String> queue = new LinkedList<>();
public synchronized void addTask(String s) {
this.queue.add(s);
this.notifyAll();
}
public synchronized String getTask() throws InterruptedException {
while (queue.isEmpty()) {
this.wait();
}
return queue.remove();
}
}
- 1
爱竹子的大黑熊
运行后的结果:(每次运行结果不一样)