并发编程 Worker Thread模式

本文将介绍并发编程中的 Worker Thread 模式。

一、什么是 Worker Thread 模式?

可以将 Worker Thread 模式理解为:维护一批工人,这批工人会共同完成到来的任务。

二、示例 - echo

下面将展示网络编程中最简单的 echo 程序,它将原封不动地返回请求,如下:

与 Thread-Per-Message 模式的实现相比,它会创建一个线程池,并将任务交由线程池处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
ExecutorService executorService = Executors.newFixedThreadPool(500);
final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open().bind(new InetSocketAddress(8080));
try {
while (true) {
// 接收请求
SocketChannel socketChannel = serverSocketChannel.accept();
// 提交任务
executorService.execute(() -> {
try {
// 读
ByteBuffer readBuffer = ByteBuffer.allocateDirect(1024);
socketChannel.read(readBuffer);
//模拟处理请求
Thread.sleep(2000);
// 写
ByteBuffer writeBuffer = (ByteBuffer)readBuffer.flip();
socketChannel.write(writeBuffer);
// 关闭Socket
socketChannel.close();
} catch(Exception e) {
throw new UncheckedIOException(e);
}
})
}
} finally {
serverSocketChannel.close();
executorService.shutdown();
}

参考

  • Java 并发编程实战