多线程——12队列模式

目标

  • 实现一个队列来存储任务, 然后启动一个生产者向队列添加任务, 启动服务者消费队列里面的任务

主要角色

  • 任务是什么: 这里客户端的请求所以使用request
  • 任务的队列:requestQueue在这里面get如果对列为空让get的线程wait, 同理put就直接notifyAll
  • 谁来处理任务:ServerThread
  • 谁来发起请求:ClientThread

代码实现

  • Request
public class Request {

    private final String values;

    public Request(String values) {
        this.values = values;
    }

    public String getValues() {
        return values;
    }
}
  • RequestQueue
public class RequestQueue {

    private final LinkedList<Request> queue = new LinkedList<>();


    public Request getRequest() {
        synchronized (queue) {
            while (queue.isEmpty()) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    break;
                }
            }
            return queue.removeFirst();
        }
    }


    public void putRequest(Request request) {
        synchronized (queue) {
            queue.addLast(request);
            queue.notifyAll();
        }
    }
}
  • ClientThread
public class ClientThread extends Thread {
    private final RequestQueue queue;
    private final String sendValue;

    public ClientThread(RequestQueue queue, String sendValue) {
        this.queue = queue;
        this.sendValue = sendValue;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            System.out.println("client send message -> " + sendValue + i);
            queue.putRequest(new Request(sendValue + i));
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        RequestQueue queue = new RequestQueue();
        ServerThread serverThread =
                new ServerThread(queue);
        ClientThread clientThread =
                new ClientThread(queue, "send value");
        serverThread.start();
        clientThread.start();
    }
}
  • ServerThread
public class ServerThread extends Thread {

    private final RequestQueue queue;

    public ServerThread(RequestQueue queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        while (true) {
            Request request = queue.getRequest();
            if (request == null)
                continue;
            System.out.println("server consumer" + request.getValues());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值