多线程模型
多线程模型
多线程模型与单线程模型最大的区别是有专门的一组

多线程模型中有一个专门的线程负责监听和处理所有的客户端连接,网络
代码案例
public class Acceptor implements Runnable {
private Selector selector;
private ServerSocketChannel serverSocketChannel;
public Acceptor(Selector selector, ServerSocketChannel serverSocketChannel) {
this.selector = selector;
this.serverSocketChannel = serverSocketChannel;
}
@Override
public void run() {
try {
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println("有客户端连接上来了," + socketChannel.getRemoteAddress());
socketChannel.configureBlocking(false);
SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);
// 修改此处就可以切换成多线程模型了
selectionKey.attach(new WorkerHandlerThreadPool(socketChannel));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class WorkerHandlerThreadPool implements Runnable {
static ExecutorService pool = Executors.newFixedThreadPool(2);
private SocketChannel socketChannel;
public WorkerHandlerThreadPool(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
}
@Override
public void run() {
try {
System.out.println("WorkerHandlerThreadPool thread :" + Thread.currentThread().getName());
ByteBuffer buffer = ByteBuffer.allocate(1024);
socketChannel.read(buffer);
pool.execute(new Process(socketChannel, buffer));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Process implements Runnable {
private SocketChannel socketChannel;
private ByteBuffer byteBuffer;
public Process(SocketChannel socketChannel, ByteBuffer byteBuffer) {
this.byteBuffer = byteBuffer;
this.socketChannel = socketChannel;
}
@Override
public void run() {
try {
System.out.println("sleep 10s");
Thread.sleep(10000);
System.out.println("process thread:" + Thread.currentThread().getName());
String message = new String(byteBuffer.array(), StandardCharsets.UTF_8);
System.out.println(socketChannel.getRemoteAddress() + "发来的消息是:" + message);
socketChannel.write(ByteBuffer.wrap("你的消息我收到了".getBytes(StandardCharsets.UTF_8)));
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
有客户端连接上来了,/127.0.0.1:64797
有客户端连接上来了,/127.0.0.1:64800
WorkerHandlerThreadPool thread :main
sleep 10s
process thread:pool-1-thread-1
/127.0.0.1:64797发来的消息是:I am one
WorkerHandlerThreadPool thread :main
sleep 10s
WorkerHandlerThreadPool thread :main
sleep 10s
process thread:pool-1-thread-2
/127.0.0.1:64800发来的消息是:I am two
process thread:pool-1-thread-1
/127.0.0.1:64797发来的消息是:hah
*/
单