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<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();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值