目标
- 实现一个队列来存储任务, 然后启动一个生产者向队列添加任务, 启动服务者消费队列里面的任务
主要角色
- 任务是什么: 这里客户端的请求所以使用request
- 任务的队列:requestQueue在这里面get如果对列为空让get的线程wait, 同理put就直接notifyAll
- 谁来处理任务:ServerThread
- 谁来发起请求:ClientThread
代码实现
public class Request {
private final String values;
public Request(String values) {
this.values = values;
}
public String getValues() {
return values;
}
}
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();
}
}
}
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();
}
}
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();
}
}
}
}