java 自己编写线程池_简单的自定义线程池(java)

packagethreadpool_test;importjava.util.concurrent.BlockingQueue;importjava.util.concurrent.LinkedBlockingDeque;importjava.util.concurrent.TimeUnit;/*** 自定义一个简单的线程池

*

* ***/

public classThreadPool {private static final int coreThreadNum=3;//核心线程数

private static final int maxThreadNum=8;//最大线程数

private boolean working=true;//打开、关闭线程池

private BlockingQueue workThreads=new LinkedBlockingDeque<>(maxThreadNum);//当前工作线程

private BlockingQueue tasks=new LinkedBlockingDeque<>(10);//任务队列

public void execute(Runnable task) throwsInterruptedException{if(task==null) throw newNullPointerException();int workNum=workThreads.size();if(workNum

Worker worker=newWorker(task);

Thread thread=newThread(worker);

workThreads.offer(thread);//特殊值,add会抛出异常

thread.start();

}else if(tasks.size()<10){//任务池还没满,就把任务放进任务池里

tasks.offer(task);

}else if(workNum

Worker worker=newWorker();

Thread thread=newThread(worker);

System.out.println("开启新线程了"+thread.getName());

workThreads.offer(thread);

thread.start();

}else{

System.out.println("放弃该任务");return;

}

}public voidshutDown(){this.working=false;for(Thread worker:workThreads){

System.out.println("终止线程名:"+worker.getName());

worker.interrupt();

}

System.out.println("终止线程池线程");

Thread.currentThread().interrupt();

}private class Worker implements Runnable{//任务包装类

privateRunnable task_origal;publicWorker() {

}publicWorker(Runnable task) {this.task_origal=task;

}

@Overridepublic voidrun() {if(task_origal!=null)

task_origal.run();while(working){try{

Runnable task=tasks.take();//阻塞提取任务,阻塞状态下的中断并不会真的中断

task.run();

}catch(InterruptedException e) {

System.out.println("真的终止了");

Thread.currentThread().interrupt();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值