Java实现一个简单的线程池

最近研究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 pool;
	public MyThread(List 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 pool = new LinkedList();
	
	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


你可能感兴趣的:(Java源码,线程池,java)