對比單執行緒和多執行緒執行效率
阿新 • • 發佈:2021-06-23
@Test public void testThreadPool() throws InterruptedException { Long start = System.currentTimeMillis(); System.out.println("普通開始時間-"+start); for (int i = 0; i < 1000; i++) { // System.out.println("普通----" + i); Thread.sleep(10l); } Long end = System.currentTimeMillis(); System.out.println("普通結束時間-"+(end-start)); ExecutorService executors = new ThreadPoolExecutor(10, 15, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000), new ThreadPoolExecutor.CallerRunsPolicy()); Long start1 = System.currentTimeMillis(); System.out.println("多執行緒執行執行緒開始時間-"+System.currentTimeMillis()); for (int ill = 0; ill < 1000; ill++) { final int i = ill; executors.execute(new Runnable() { @Override public void run() { // System.out.println("執行執行緒----" + i); try { Thread.sleep(10l); } catch (InterruptedException e) { e.printStackTrace(); } } }); } executors.shutdown(); while(true){ if(executors.isTerminated()){ Long end1 = System.currentTimeMillis(); System.out.println("多執行緒執行執行緒結束時間-"+(end1-start1)); System.out.println("所有的子執行緒都結束了!"); break; } Thread.sleep(10); } }