Java1.6多線程之同步方法

來源:互聯網
上載者:User
package com.starit.open.main;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** *  * @author wenin819 *  *         Callable 和 Future介面 *         Callable是類似於Runnable的介面,實現Callable介面的類和實現Runnable的類都是可被其它線程執行的任務。 *         Callable和Runnable有幾點不同:  *         (1)Callable規定的方法是call(),而Runnable規定的方法是run(). *         (2)Callable的任務執行後可傳回值,而Runnable的任務是不能傳回值的。 *         (3)call()方法可拋出異常,而run()方法是不能拋出異常的。  *         (4)運行Callable任務可拿到一個Future對象, *         Future 表示非同步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。 *         通過Future對象可瞭解任務執行情況,可取消任務的執行,還可擷取任務執行的結果。 *  */public class CallableThreadSync implements Runnable{private static final ExecutorService es = Executors.newFixedThreadPool(5);public static class ItemThread implements Callable<Integer> {public int addNum;public ItemThread(int addNum) {this.addNum = addNum;}@Overridepublic Integer call() {try {Thread.sleep(addNum * 1000);} catch (InterruptedException e) {e.printStackTrace();}return addNum * 2;}}public static void main(String[] args) {CallableThreadSync test = new CallableThreadSync();long startTime = System.currentTimeMillis();new Thread(test, "thread1").start();new Thread(test, "thread2").start();long endTime = System.currentTimeMillis();System.out.println("main:用時" + (endTime - startTime) / 1000 + "秒");}public void run() {long startTime = System.currentTimeMillis();List<ItemThread> itemThreads = new ArrayList<CallableThreadSync.ItemThread>(3);ItemThread itemThread = null;for(int i = 0; i < 3; i++) {itemThread = new ItemThread(i + 1);itemThreads.add(itemThread);}List<Future<Integer>> futureList = null;try {futureList = es.invokeAll(itemThreads);} catch (InterruptedException e1) {e1.printStackTrace();}Integer result = 1;for(Future<Integer> future : futureList) {try {result += future.get();} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}String infoMsg = Thread.currentThread().getName() + ":";long endTime = System.currentTimeMillis();System.out.println(infoMsg + result + "(用時" + (endTime - startTime) / 1000 + "秒)");}@Overrideprotected void finalize() throws Throwable {es.shutdownNow();super.finalize();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.