欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

制作一个简单的任务队列(使用阻塞队列)

程序员文章站 2022-07-10 18:44:07
充分利用阻塞队列的特性,队列中没有任务时,让线程阻塞。代码如下: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 Bloc...

充分利用阻塞队列的特性,队列中没有任务时,让线程阻塞。代码如下:

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 {
            /* 队列已满,阻塞 */
            TASK_QUEUE.put(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

任务接口:

/**
 * @Author river66
 * @Date 2020/10/25 8:38
 */
public interface Task {
    void handle();
}

具体的任务示例:

/**
 * @Author river66
 * @Date 2020/10/25 9:18
 */
public class DoSomethingTask implements Task {

    private String something;

    @Override
    public void handle() {
        System.out.println(something);
    }

    public void setSomething(String something) {
        this.something = something;
    }
}

测试任务的执行情况:

DoSomethingTask codeTask = new DoSomethingTask();
codeTask.setSomething("敲代码");
DoSomethingTask romanticTask = new DoSomethingTask();
romanticTask.setSomething("谈恋爱");
DoSomethingTask sleepTask = new DoSomethingTask();
sleepTask.setSomething("睡懒觉");
Scanner scanner = new Scanner(System.in);
while (true) {
    String choice = scanner.next();
    switch (choice) {
        case "1":
            MyTaskQueue.getInstance().put(romanticTask);
            break;
        case "2":
            MyTaskQueue.getInstance().put(sleepTask);
            break;
        default:
            MyTaskQueue.getInstance().put(codeTask);

    }
}

打印:

1
谈恋爱
2
睡懒觉
3
敲代码
4
敲代码
5
敲代码
6
敲代码

 

本文地址:https://blog.csdn.net/river66/article/details/109270110

相关标签: 知识篇