300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java 多线程任务队列_精简的java 线程池与任务队列

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

时间:2024-01-09 20:48:12

相关推荐

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

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 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。