天天看點

java 多線程Callable和Runable執行順序問題詳解

毫無疑問 runnable會進行異步執行,此處不多數,主要說明callable的使用,看執行個體:

1、

public class threadtest {

    public static void main(string[] args) throws interruptedexception, executionexception {

        executorservice executor = executors.newfixedthreadpool(4);

        mytread m1 = new mytread();

        future f = executor.submit(m1);

        // system.out.println(f.get());

        executor.shutdown();

        system.out.println("主線程執行完了");

    }

}

class mytread implements callable<string> {

    @override

    public string call() {

        try {

            system.out.println("線程排程:" + thread.currentthread());

            timeunit.seconds.sleep(3);

        } catch (interruptedexception e) {

            e.printstacktrace();

        }

        return "123";

此程式雖然擷取了call方法的傳回值,但是沒有做處理,是以主線程main和m1同時執行,執行結果如下:

主線程執行完了

線程排程:thread[pool-1-thread-1,5,main]

2、

        system.out.println(f.get()); // 進行了輸出

在2中,對m1中call方法的傳回值在main中進行了處理(輸出),是以在此種情況下,main需要等待m1執行完,再繼續執行,執行結果如下

123

3、再看當主線程中同時啟動兩個由callable生成的線程時

        mytread2 m2 = new mytread2();

        long time1 = timeunit.milliseconds.toseconds(system.currenttimemillis());

        future f2 = executor.submit(m2);

        system.out.println(f.get()); // 進行了輸出m1

        system.out.println(f2.get()); // 進行了輸出m2

        long time2 = timeunit.milliseconds.toseconds(system.currenttimemillis());

        system.out.println("主線程等待了" + (time2 - time1) + "秒");

class mytread2 implements callable<string> {

            system.out.println("線程排程2:" + thread.currentthread());

        return "abc";

當不對m1和m2做輸出時,main和m1、m2并發執行,當對m1和m2中任意一個的傳回值進行處理的時候,main需要等待,但是m1和m2之前仍然是并發執行,執行結果如下:

線程排程2:thread[pool-1-thread-2,5,main]

abc

主線程等待了3秒

特别說明:尊重作者的勞動成果,轉載請注明出處哦~~~http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt125