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

本文展示了如何使用Java实现一个简单的线程池和任务队列。通过创建一个`WorkQueue`类,它包含一个线程池数组和一个LinkedList作为任务队列。每个工作线程在队列为空时等待,当有新任务添加到队列时,被唤醒并执行任务。在main方法中,创建了10个工作线程和20个任务进行测试。
摘要由CSDN通过智能技术生成

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   }

c643ba0ef59428b06737509fcbeb4644.png

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   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值