JAVA並發編程8_線程池的使用,java線程

來源:互聯網
上載者:User

JAVA並發編程8_線程池的使用,java線程
不使用線程池

1.串列執行任務

class SingleThreadWebServer {public static void main(String[] args) {ServerSocket socket = new ServerSocket(80);while (true) {Socket conn = socket.accept();handleRequest(conn);}}}

需要等待一個串連處理完成再處理下一個使用者請求,無法提供高的輸送量和快速的響應速度,cpu利用率低。

2.為每個請求啟動一個新線程

class ThreadPerTaskWebServer {public static void main(String[] args) {ServerSocket socket = new ServerSocket(80);while (true) {final Socket conn = socket.accept();Runnable runnable = new Runnable() {@Overridepublic void run() {handleRequest(conn);}};new Thread(runnable).start();}}}

為每個使用者請求開啟新線程,將任務的處理從主線程中分離出來,使得任務可以平行處理。提升了串列執行的效能和響應速度。

不足:

線程生命週期的開銷非常高。線程的建立和銷毀都是有代價的,不同平台開銷也不同。

資源消耗。太多線程會消耗系統資源,如空閑線程的記憶體佔用,大量線程競爭CPU時產生其他效能開銷等。

穩定性。可建立線程數會受到限制。

Executor架構

任務是一組邏輯工作單元,而線程則是使任務非同步執行的機制。前面兩種方式都存在一些嚴格的限制:串列執行的問題在於糟糕的響應性和輸送量,而“為每個任務分配一個線程”的問題在於資源管理的複雜性。

java.util.concurrent包提供了靈活的線程池實現作為Executor架構的一部分

public interface Executor {    void execute(Runnable command);}

Executor是個簡單的介面,但卻為靈活且強大的非同步任務執行架構提供了基礎,該架構能支援多種不同類型的任務執行策略。它提供了一種標準的方法將任務的提交過程和執行過程解耦開來,並用Runnable來表示任務。Executor的實現還提供了對生命週期的支援,以及統計資訊、應用管理機制和效能監控等機制。

基於線程池的Web伺服器

public class TaskExecutionWebServer {    private static final int NTHREADS = 100;    private static final Executor exec =             Executors.newFixedThreadPool(NTHREADS);    public static void main(String[] args) throws IOException {        ServerSocket server = new ServerSocket(80);        while (true){            final Socket connection = server.accept();            Runnable task = new Runnable() {                @Override                public void run() {                    handlerRequest(connection);                }            };            exec.execute(task);        }    }}

利用Executor提供的架構,我們可以修改TaskExecutionWebServer為類似於SingleThreadWebServer的單線程(串列執行)行為。

public class SingleThreadExecutor implements Executor{@Overridepublic void execute(Runnable command) {command.run();}}

同樣的,我們也可以修改TaskExecutionWebServer為類似於ThreadPerTaskWebServer的多線程(為每一個請求啟動一個線程)行為。

public class ThreadPerTaskExecutor implements Executor{@Overridepublic void execute(Runnable command) {new Thread(command).start();}}

可以通過Executor中的靜態Factory 方法建立線程池

建立固定長度的線程池,每當提交一個任務時就建立一個線程,直到達到線程池的最大數量,若有線程發生異常,則會重新建立

public static ExecutorServicenewFixedThreadPool(int nThreads) {...}

建立單個線程來執行任務,若該線程發生異常,會建立一個新的線程。該池可按順序執行隊列中的任務(如FIFO,LIFO,優先順序等)

public static ExecutorServicenewSingleThreadExecutor() {...}

該線程池無長度限制,線上程過多時會回收,過少時會建立

public static ExecutorServicenewCachedThreadPool() {...}

建立一個固定長度的線程池,並以延遲或定時的方式執行任務

public static ScheduledExecutorServicenewScheduledThreadPool{...}

Executor是最頂層的介面

ExecutorService繼承自Executor,添加了一些用語生命週期管理的方法和一些任務提交的方法。

AbstractExecutorService實現了ExecutorService介面,ThreadPollExecutor繼承自AbstractExecutorService。

Callable和Future

使用Runnable有很大的局限性,不能返回一個值或拋出一個受檢查的異常。這時Callable就可以勝任。使用Callable可以返貨線程啟動並執行結果,這個結果在Fuuture裡面通過get方法獲得。

Future表示一個任務的生命週期,並提供了相應的方法判斷是否已經完成或取消以及擷取任務的結果和取消任務。get方法的行為取決於任務的狀態,如果任務已經完成,那麼get立即返回或拋出Exception。如果沒有完成,get將阻塞並直到任務完成。若果任務拋出了異常那麼get也會拋出異常。

public interface Callable<V> {    V call() throws Exception;}public interface Future<V> {    boolean cancel(boolean mayInterruptIfRunning);    boolean isCancelled();    boolean isDone();    V get() throws InterruptedException, ExecutionException;    V get(long timeout, TimeUnit unit)        throws InterruptedException, ExecutionException, TimeoutException;}

可以通過多種方法建立一個Future來描述任務。ExecutorService裡面的所有submit方法都將返回一個Future,從而講一個Runnable或Callable提交給Executor,並得到一個Future用於獲得任務執行結果或取消任務。

class MyCallable implements Callable<String> {@Overridepublic String call() {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}return "haha-callable";}}public class TestExecutor {public static void main(String[] args) {List<Future<String> > futureList = new ArrayList<Future<String>>();ExecutorService exec = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {futureList.add(exec.submit(new MyCallable()));}for (Future<String> future : futureList) {try {System.out.println(future.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}}

輸出

haha-callablehaha-callablehaha-callablehaha-callablehaha-callable

還可以顯式的為某個指定的Runnable或Callable執行個體化一個FutureTask,FutureTask實現了Runnable,因此可以交給Thread或者Executor來執行。

class MyCallable implements Callable<String> {@Overridepublic String call() {try {Random r = new Random();TimeUnit.SECONDS.sleep(r.nextInt(5));} catch (InterruptedException e) {e.printStackTrace();}return "haha-callable";}}public class TestExecutor {public static void main(String[] args) {List<Future<String> > futureList = new ArrayList<Future<String>>();ExecutorService exec = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {FutureTask<String> future = new FutureTask<String>(new MyCallable());futureList.add(future);new Thread(future).start();}for (Future<String> future : futureList) {try {System.out.println(future.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}}

如同上面的例子,向Executor提交了一組任務,並且希望計算完成後獲得結果。可以按照上面的方法保留每個任務相關聯的Future,然後在for迴圈裡面使用get方法,存在的問題是get方法會阻塞等待返回結果。因此會按照任務添加進去的順序等待計算的結果。

比如如果添加進去的任務第一個任務耗時5s,第二個4s…第五個1s,輸出這五個任務的計算結果卻不能按照先擷取先執行完的任務的值,因為get方法會阻塞直到任務完成。

class MyCallable implements Callable<String> {private int id;public MyCallable(int id) {this.id = id;}@Overridepublic String call() {try {TimeUnit.SECONDS.sleep(5-id);} catch (InterruptedException e) {e.printStackTrace();}return id + " -- haha-callable";}}public class TestExecutor {public static void main(String[] args) {List<Future<String> > futureList = new ArrayList<Future<String>>();ExecutorService exec = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {futureList.add(exec.submit(new MyCallable(i)));}for (Future<String> future : futureList) {try {System.out.println(future.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}}

5S鐘後會馬上列印,並且不是先完成的先列印

0 -- haha-callable1 -- haha-callable2 -- haha-callable3 -- haha-callable4 -- haha-callable

事實上可以按照上面的方法保留每個任務相關聯的Future,然後在for迴圈裡面反覆使用get方法,同時將timeout設定為0,或者判斷當前任務isDone再get,通過輪詢的方式判斷任務是否完成。這種方法孫然可行但是卻非常繁瑣。

class MyCallable implements Callable<String> {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");private int id;public MyCallable(int id) {this.id = id;}@Overridepublic String call() {try {TimeUnit.SECONDS.sleep(5-id);} catch (InterruptedException e) {e.printStackTrace();}return df.format(new Date()) +" " + id + " -- haha-callable";}}public class TestExecutor {public static void main(String[] args) {List<Future<String> > futureList = new ArrayList<Future<String>>();List<Future<String> > finishedFutureList = new ArrayList<Future<String>>();ExecutorService exec = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {futureList.add(exec.submit(new MyCallable(i)));}while (finishedFutureList.size()<5) {for (Future<String> future : futureList) {if (finishedFutureList.contains(future))continue;try {if (future.isDone()) {System.out.println(future.get(0,TimeUnit.SECONDS));finishedFutureList.add(future);}} catch (InterruptedException | ExecutionException | TimeoutException e) {e.printStackTrace();}}}}}

每隔一秒輸出,並且先完成的任務先列印

2015-08-24 10:12:08 4 -- haha-callable2015-08-24 10:12:09 3 -- haha-callable2015-08-24 10:12:10 2 -- haha-callable2015-08-24 10:12:11 1 -- haha-callable2015-08-24 10:12:12 0 -- haha-callable

通過輪詢的方式可以將先完成的任務結果得到。但是比較麻煩。另一種更好的方式是完成服務(CompletetionService)

class MyCallable implements Callable<String> {SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");private int id;public MyCallable(int id) {this.id = id;}@Overridepublic String call() {try {TimeUnit.SECONDS.sleep(5 - id);} catch (InterruptedException e) {e.printStackTrace();}return df.format(new Date()) + " " + id + " -- haha-callable";}}public class TestExecutor {public static void main(String[] args) {ExecutorService exec = Executors.newCachedThreadPool();CompletionService<String> completionService = new ExecutorCompletionService<String>(exec);for (int i = 0; i < 5; i++) {completionService.submit(new MyCallable(i));} for (int j = 0; j < 5; j++) {try {Future<String> f = completionService.take();System.out.println(f.get());} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}}
每隔一秒輸出,並且先完成的任務先列印

2015-08-24 10:29:53 4 -- haha-callable2015-08-24 10:29:54 3 -- haha-callable2015-08-24 10:29:55 2 -- haha-callable2015-08-24 10:29:56 1 -- haha-callable2015-08-24 10:29:57 0 -- haha-callable

CompletetionService通過take取出已經完成的任務,被封裝成Future。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.