iothreadpoolmanager.java
来自「面向对象的设计思想」· Java 代码 · 共 63 行
JAVA
63 行
import java.io.*;
import java.net.*;
import java.util.*;
public class IoThreadPoolManager implements IoStrategy{
private DrawModel drawModel;
private ArrayList clientIoThreadList;
/** Creates new IoThreadAllocator */
public IoThreadPoolManager(DrawModel draw) {
//** 1 Initialize Broker
this.drawModel = draw;
//** 2 Creat thread pool
clientIoThreadList = new ArrayList(10);
//** 3 Creat first thread
this.createNewThread();
}
public void ioService(Socket socket) {
// find an available IoThread object
IoThread ioThread;
boolean idleThreadFound = false;
for (int i=0; i<clientIoThreadList.size(); i++){
//** 4 Get a thread from thread pool
ioThread = (IoThread) clientIoThreadList.get(i);
if (ioThread.isIdle()){
//* 5 Start the thread
ioThread.setSocket(socket);
idleThreadFound = true;
break;
}
}
if (!idleThreadFound) {
ioThread = this.createNewThread();
ioThread.setSocket(socket);
}
}
private IoThread createNewThread() {
DrawServer drawServer = new DrawServer(drawModel);
// ** 7 Create an IoThread object
IoThread ioThread = new IoThread(drawServer);
//** 8 Start the thread
ioThread.start();
//** 9 Add thread to list
clientIoThreadList.add(ioThread);
try {
//sleep to give newly created thread chance to run
Thread.sleep(1000);
} catch(Exception e) {
e.printStackTrace();
}
return ioThread;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?