1 public class CalcTest{ 2 3 private volatile int beforeValue = 0;//最後一個啓動線程須要計算範圍的的起始值 4 private volatile boolean isStop = false;//是否完成了全部的輸出 5 private volatile boolean isChangeBeforeValue = true;//是否有線程啓動成功,並改變了beforeValue 6 private volatile int threadCount = 0;//全部線程總數 7 private volatile Integer nowThreadCount = 0;//當前計算線程總數 8 private final int minValue = 0;//範圍最小值 9 private final int maxValue = 100000000;//範圍最大值 10 private final int speed = 10000;//每個線程須要計算數字的個數,改值設置的越小,每個子線程進行計算所需時間就會相應減小,當前處於計算的總子線程數也就相應減少 11 private LinkedBlockingQueue<String> result = new LinkedBlockingQueue<>();//計算結果存放隊列 12 13 @Test 14 public void test_calc() { 15 Timestamp startTime = new Timestamp(System.currentTimeMillis());//開始時間 16 final ExecutorService calcThreadPool = Executors.newFixedThreadPool(1);//進行拆分計算的固定緩存池 17 calcThreadPool.execute(new Runnable() { 18 @Override 19 public void run() { 20 calc(); 21 calcThreadPool.shutdown(); 22 } 23 }); 24 //從結果隊列中時時取出結果 25 String nextResult; 26 while (!isStop || !result.isEmpty()) { 27 nextResult = result.poll(); 28 if (nextResult == null) { 29 continue; 30 } 31 System.out.println("now calc thread total count:" + nowThreadCount + " , now beforeValue:" + beforeValue + " ," + nextResult); 32 } 33 //計算完了統計一下 34 System.out.println("------------------- ok ---------------------"); 35 System.out.println(result); 36 Timestamp endTime = new Timestamp(System.currentTimeMillis()); 37 System.out.println(startTime + "-->" + endTime); 38 System.out.println("共開起線程總數:" + threadCount); 39 System.out.println((endTime.getTime() - startTime.getTime()) / 1000 + "秒"); 40 } 41 42 public void calc() { 43 beforeValue = minValue; 44 while (true) { 45 if (isChangeBeforeValue) { 46 threadCount++; 47 isChangeBeforeValue = false; 48 try { 49 synchronized (nowThreadCount) { 50 nowThreadCount++; 51 } 52 final ExecutorService calcThreadPool = Executors.newCachedThreadPool(); 53 calcThreadPool.execute(new Runnable() { 54 @Override 55 public void run() { 56 int firstValue = beforeValue + 1; 57 int lastValue = firstValue + speed; 58 final int endValue = (lastValue > maxValue ? maxValue : lastValue); 59 isStop = endValue == maxValue; 60 beforeValue = endValue; 61 isChangeBeforeValue = true; 62 StringBuilder sb = new StringBuilder(); 63 for (int i = firstValue; i <= endValue; i++) { 64 String str = " " + i + "平方:" + Math.pow(i, 2); 65 sb.append(str); 66 } 67 try { 68 result.put(" calc thread " + Thread.currentThread().getId() + " => " + sb.toString()); 69 sb.setLength(0); 70 } catch (InterruptedException e) { 71 e.printStackTrace(); 72 } 73 synchronized (nowThreadCount) { 74 nowThreadCount--; 75 } 76 calcThreadPool.shutdown(); 77 } 78 }); 79 } catch (Exception e) { 80 System.out.println(e.getMessage()); 81 break; 82 } 83 } 84 if (isStop && !result.isEmpty()) { 85 break; 86 } 87 } 88 } 89 } 90