欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java線程池用法實戰(zhàn)案例分析

 更新時間:2019年10月25日 12:00:06   作者:cakincqm  
這篇文章主要介紹了Java線程池用法,結(jié)合具體案例形式分析了java線程池創(chuàng)建、使用、終止等相關(guān)操作技巧與使用注意事項,需要的朋友可以參考下

本文實例講述了Java線程池用法。分享給大家供大家參考,具體如下:

一 使用newSingleThreadExecutor創(chuàng)建一個只包含一個線程的線程池

1 代碼

import java.util.concurrent.*;
public class executorDemo
{
  public static void main( String[] args )
  {    
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);
    }); 
  }
}

2 運行

Hello pool-1-thread-1

二 含有終止方法的線程池

1 代碼

import java.util.concurrent.*;
public class executorShutdownDemo {
  public static void main( String[] args ) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);
    });
    try {
      TimeUnit.SECONDS.sleep(3);
      System.out.println("嘗試關(guān)閉線程執(zhí)行器...");
      executor.shutdown();
      executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      System.err.println("關(guān)閉任務被中斷!");
    } finally {
      if (!executor.isTerminated()) {
        System.err.println("取消未完成的任務");
        executor.shutdownNow();
      }
      System.out.println("任務關(guān)閉完成");
    }
  }
}

2 運行

Hello pool-1-thread-1
嘗試關(guān)閉線程執(zhí)行器...
任務關(guān)閉完成

3 說明

shutdown只是將線程池的狀態(tài)設置為SHUTWDOWN狀態(tài),正在執(zhí)行的任務會繼續(xù)執(zhí)行下去,沒有被執(zhí)行的則中斷。

shutdownNow則是將線程池的狀態(tài)設置為STOP,正在執(zhí)行的任務則被停止,沒被執(zhí)行任務的則返回。

舉個工人吃包子的例子:一個廠的工人(Workers)正在吃包子(可以理解為任務)。

假如接到shutdown的命令,那么這個廠的工人們則會把手頭上的包子給吃完,沒有拿到手里的籠子里面的包子則不能吃!

而如果接到shutdownNow的命令以后呢,這些工人們立刻停止吃包子,會把手頭上沒吃完的包子放下,更別提籠子里的包子了。

awaitTermination(long timeOut, TimeUnit unit)

當前線程阻塞,直到

  • 等所有已提交的任務(包括正在跑的和隊列中等待的)執(zhí)行完
  • 或者等超時時間到
  • 或者線程被中斷,拋出InterruptedException

然后返回true。

更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java進程與線程操作技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設計有所幫助。

相關(guān)文章

最新評論