最精简的java 线程池与任务队列

  1. import java.util.*;  
  2.   
  3. public class WorkQueue {  
  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 < nThreads; 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.                     }  
  37.                     r = (Runnable) queue.removeFirst();// 有任务时,取出任务  
  38.                 }  
  39.                 try {  
  40.                     r.run();// 执行任务  
  41.                 } catch (RuntimeException e) {  
  42.                     // You might want to log something here  
  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.   
  59. class Mytask implements Runnable {// 任务接口  
  60.     public void run() {  
  61.         String name = Thread.currentThread().getName();  
  62.         try {  
  63.             Thread.sleep(100);// 模拟任务执行的时间  
  64.         } catch (InterruptedException e) {  
  65.         }  
  66.         System.out.println(name + " executed OK");  
  67.     }  
  68. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值