package com.ly.thread;
import java.util.LinkedList;
/**线程池
* @author 牵手无奈
* date:2015-10-14
*
*/
public class ThreadPool extends ThreadGroup{
private int poolSize;
private static int threadPoolID;
private boolean isClosed;
private LinkedList<Runnable> workQueue;//工作任务队列
private int ThreadID;
public ThreadPool(int size){
super("ThreadPool id="+threadPoolID++);
this.poolSize=size;
setDaemon(true);
workQueue = new LinkedList<>();
for(int i=0;i<poolSize;i++){
new WorkThread().start();//先运行多个线程,随时准备通过它来执行任务
}
}
/**执行提交的任务
* @param task
*/
public synchronized void execute(Runnable task){
if(isClosed){
throw new IllegalThreadStateException();
}else{
workQueue.add(task);
notify();//唤醒在等待获取任务执行的线程
}
}
public synchronized Runnable getTask() throws InterruptedException{
while(workQueue.size()==0){
if(isClosed) return null;
wait();
System.out.println("唤醒了一个线程");
}
return workQueue.removeFirst();
}
public synchronized void close(){
if(!isClosed){
isClosed=true;
workQueue.clear();
}
interrupt();
}
public void join(){
synchronized (this) {
isClosed=true;
notifyAll();
}
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for(int i=0;i<count;i++){
try {
threads[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class WorkThread extends Thread{
public WorkThread(){
super(ThreadPool.this,"WorkThread"+ThreadID++);
}
@Override
public void run() {
while (!isInterrupted()) {
Runnable task = null;
try {
task=getTask();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(task==null){
return;
}else{
task.run();
}
}
}
}
public static void main(String[] args){
ThreadPool tp = new ThreadPool(3);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for( int i=0;i<10;i++){
tp.execute(new Runnable() {
@Override
public void run() {
System.out.println("1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
tp.join();
}
}
java线程池
最新推荐文章于 2024-07-13 22:56:10 发布