最近研究nio,顺便实现一个线程池。
package test;
import java.io.IOException;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException, ParseException, InterruptedException {
ThreadPoolManager tpm = new ThreadPoolManager();
tpm.createThreadPool(3);
tpm.startAllThread();
Thread.sleep(3000);
while(true) {
MyThread tmp = tpm.getWorker();
if(tmp != null) {
tmp.service();
Thread.sleep(1000);
}
}
}
}
class MyThread extends Thread {
List<MyThread> pool;
public MyThread(List<MyThread> pool) {
this.pool = pool;
}
public synchronized void run() {
System.out.println("i started " + Thread.currentThread());
while(true) {
try {
this.wait();
} catch (Exception e) {
}
System.out.println("i start to work" + " " + Thread.currentThread());
this.pool.add(this);
System.out.println("i finished my work " + Thread.currentThread());
}
}
public synchronized void service() {
this.notify();
}
}
class ThreadPoolManager {
private List<MyThread> pool = new LinkedList<MyThread>();
public synchronized MyThread getWorker() {
MyThread worker = null;
if(pool.size() > 0) {
worker = pool.remove(0);
}
return worker;
}
public void createThreadPool(int maxSize) {
for(int i=0;i<maxSize;i++) {
this.pool.add(new MyThread(pool));
}
}
public void startAllThread() {
for(MyThread t : pool) {
t.start();
}
}
}