去哪儿第三题01
练手,仿着写的
1 package test; 2 3 import java.util.LinkedList; 4 5 public class Qunaer031 { 6 7 public int nThreads; //线程池中的线程数 8 public PoolThreads []pool; //线程池 9 public LinkedList<workTask> queue; //消息队列 10 11 public Qunaer031(int nThreads) { 12 super(); 13 this.nThreads = nThreads; 14 queue = new LinkedList<workTask>(); 15 pool = new PoolThreads[nThreads]; 16 17 for(int i=0;i<nThreads;i++){ 18 pool[i] = new PoolThreads(); 19 pool[i].start(); 20 } 21 } 22 23 private void excute(Runnable r) { 24 // TODO Auto-generated method stub 25 synchronized (queue) { 26 queue.addLast((workTask) r); 27 queue.notify(); 28 } 29 } 30 31 private class PoolThreads extends Thread{ 32 33 @Override 34 public void run() { 35 // TODO Auto-generated method stub 36 super.run(); 37 38 Runnable r; 39 while(true){ 40 synchronized (queue) { 41 while(queue.isEmpty()){ 42 try { 43 queue.wait(); 44 } catch (InterruptedException e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } 48 } 49 50 r = queue.removeFirst(); 51 } 52 try { 53 r.run(); 54 } catch (Exception e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } 58 } 59 } 60 } 61 62 public static void main(String[] args) { 63 Qunaer031 q = new Qunaer031(10); 64 workTask task[] = new workTask[20]; 65 66 for(int i=0;i<20;i++){ 67 task[i] = new workTask(); 68 q.excute(task[i]); 69 } 70 } 71 72 } 73 74 75 class workTask implements Runnable{ 76 77 @Override 78 public void run() { 79 // TODO Auto-generated method stub 80 String name = Thread.currentThread().getName(); 81 try { 82 Thread.sleep(2000); 83 } catch (InterruptedException e) { 84 // TODO Auto-generated catch block 85 e.printStackTrace(); 86 } 87 88 System.out.println(name+"执行成功"); 89 } 90 91 }