充分利用阻塞队列的特性,队列中没有任务时,让线程阻塞。代码如下:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @Author river66
* @Date 2020/10/25 8:37
*/
public class MyTaskQueue implements Runnable {
private static final BlockingQueue<Task> TASK_QUEUE = new LinkedBlockingQueue<>();
private static final MyTaskQueue INSTANCE = new MyTaskQueue();
private MyTaskQueue() {
new Thread(this).start();
}
public static MyTaskQueue getInstance() {
return INSTANCE;
}
@Override
public void run() {
while (true) {
try {
/* 队列为空时阻塞线程 */
Task task = TASK_QUEUE.take();
task.handle();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void put(Task task) {
try {
/* 队列已满