实现一个简易的线程池。

定义四个类(一个内部类)。 一个任务类   一个测试类  一个线程池类包含一个内部类。

任务类

/**
 * 任务类,检查端口。
 * @author Administrator
 *
 */
public class ScannerTask {
String host;
int port;
public ScannerTask(String host, int port) {
this.host=host;
this.port=port;
}
public void startTask() {
try {
Socket socket = new Socket(host, port);
  System.out.println("The port of " + port + " is opened.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("端口被占用");
}

}


}


测试类

public class PortScannerTest {
String ip="127.0.0.1";
int beginport=1;//开始端口,开始任务
int endport=1024;//总任务,结束的端口
int nThreads=100;//线程数
public static void main(String[] args) {
PortScannerTest threadPool=new PortScannerTest();
threadPool.executMythreadPool();

}
/**
* 执行自定义线程池
*/
public void executMythreadPool() {
ThreadPool tp= new ThreadPool(nThreads);//总线程数放入线程池中
for(int port=beginport;port<=endport;port++) {//遍历
ScannerTask st=new ScannerTask(ip,port);//任务
tp.execute(st);//任务放入
}
}
}


线程池类


public class ThreadPool {
private final int nThreads;// 线程池中工作线程个数
private final PoolWorker[] threads;// 线程池数组
private final LinkedList<ScannerTask> queue;// 队列存储任务


public ThreadPool(int nThreads) {
this.nThreads = nThreads;
queue = new LinkedList<ScannerTask>();//任务存到数组里面
threads = new PoolWorker[nThreads];
//实例化工作线程并启动
for (int i = 0; i < nThreads; i++) {//启动定义线程个线程,池
threads[i] = new PoolWorker();
threads[i].start();
}
}


public void execute(ScannerTask task) {//放入任务的方法。
synchronized (queue) {//唤醒线程作用。  处在主线程当中,唤醒其他等待的线程。
queue.addLast(task);//像列队中添加任务
queue.notifyAll();// 通知唤醒所有等待线程
}
}


/**
* 工作线程:负责获取列队中任务执行

*/
private class PoolWorker extends Thread {
public void run() {
ScannerTask scanner;
while (true) {
synchronized (queue) {//这两个synchronized有什么关系
if (queue.isEmpty()) {//集合里没任务,就为空。 true 有任务,就为false;
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
scanner = (ScannerTask) queue.removeFirst();
}
scanner.startTask();
}
}
}
}

猜你喜欢

转载自blog.csdn.net/Mr_Zm1996/article/details/80209236