实现说明
底层就是类 PoisonPillShutdown、Job。
while (true) 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
consumer: pill seen, exiting loop、consumer: processed job、main: consumer finished cleanly。
常见问题
运行「毒丸对象优雅停机」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 consumer: pill seen, exiting loop、consumer: processed job、main: consumer finished cleanly 标签标明各步骤。
核心语句
Thread.currentThread().interrupt();
代码示例
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class PoisonPillShutdown {
record Job(int id, String payload) {}
// dedicated sentinel object: seeing it in the queue means there is no more work
private static final Job POISON_PILL = new Job(-1, "shutdown");
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Job> queue = new LinkedBlockingQueue<>();
Thread consumer = new Thread(() -> {
try {
while (true) {
Job job = queue.take();
if (job == POISON_PILL) {
// compare the sentinel with == so a real task with equal content is never mistaken for it
System.out.println("consumer: pill seen, exiting loop");
break;
}
System.out.println("consumer: processed job " + job.id());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumer.start();
queue.put(new Job(1, "resize-image"));
queue.put(new Job(2, "send-email"));
queue.put(POISON_PILL); // poison the queue when the producer finishes: the consumer exits on its own
consumer.join();
System.out.println("main: consumer finished cleanly");
}
}