最精简的java 线程池与任务队列
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
以下资料为java培训为大家整理:
1 import java.util.*;
2 public class WorkQueue
3 {
4 private final int nThreads;//线程池的大小
5 private final PoolWorker[] threads;//用数组实现线程池
6 private final LinkedList queue;//任务队列
7
8 public WorkQueue(int nThreads){
9 this.nThreads = nThreads;
10 queue = new LinkedList();
11 threads = new PoolWorker[nThreads];
12
13 for (int i=0; i 14 threads[i] = new PoolWorker(); 15 threads[i].start();//启动所有工作线程 16 } 17 } 18 19 public void execute(Runnable r) {//执行任务 20 synchronized(queue) { 21 queue.addLast(r); 22 queue.notify(); 23 } 24 } 25 26 private class PoolWorker extends Thread {//工作线程类 27 public void run() { 28 Runnable r; 29 while (true) { 30 synchronized(queue) { 31 while (queue.isEmpty()) {//如果任务队列中没有任务,等待 32 try{ 33 queue.wait(); 34 }catch (InterruptedException ignored){} 35 } 36 r = (Runnable) queue.removeFirst();//有任务时,取出任务 37 } 38 try { 39 r.run();//执行任务 40 }catch (RuntimeException e) { 41 // You might want to log something here 42 } 43 } 44 } 45 } 46 47 48 public static void main(String args[]){ 49 WorkQueue wq=new WorkQueue(10);//10个工作线程 50 Mytask r[]=new Mytask[20];//20个任务 51 52 for(int i=0;i<20;i++){ 53 r[i]=new Mytask(); 54 wq.execute(r[i]); 55 } 56 } 57 } 58 class Mytask implements Runnable{//任务接口 59 public void run(){ 60 String name=Thread.currentThread()。getName(); 61 try{ 62 Thread.sleep(100);//模拟任务执行的时间 63 }catch(InterruptedException e){} 64 System.out.println(name+" executed OK"); 65 } 66 }