創建線程和獲取線程結果的幾種方式


創建一個線程的方式:

創建線程的方式總體可以分為兩大類:一個是依賴於Thread類, 一個是依賴於線程池。

依賴於Thread類的創建方式:

package concurrent.newThread;

import java.util.concurrent.*;

public class NewThreadByThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1 傳入Runnable接口,lambda表達式的實現
        Thread thread = new Thread(()->{
            System.out.println("new thread by lambda implement runnable interface");
        });
        thread.start();

        //1.1 傳入Runnable接口的實現類NewThreadImplementRunnable, 注意該類並不是線程類
        class NewThreadImplementRunnable implements Runnable {
            @Override
            public void run() {
                System.out.println("new thread by implement runnable interface");
            }
        }
        NewThreadImplementRunnable tmpRunnableClass = new NewThreadImplementRunnable();
        Thread thread2 = new Thread(tmpRunnableClass);
        thread2.start();


        //2 通過繼承Thread類並重寫run方法
        class NewThreadExtendsThread extends Thread {
            @Override
            public void run() {
                System.out.println("new thread by extend thread and override run method");
            }
        }
        Thread thread1 = new NewThreadExtendsThread();
        thread1.start();


        //3 有返回值,傳入callable接口的實現類,並利用FutureTask接受消息
        class ImplementCallable implements Callable<String> {
            @Override
            public String call() throws Exception {
                System.out.println("new thread by implement callable interface");
                return "call method return finished";
            }
        }
        //FutureTask是一個實現Runnable接口的類,FutureTas內部有一個成員變量將callable接口的返回值保存起來,並通過提供get方法獲取
        FutureTask<String> futureTask = new FutureTask<>(new ImplementCallable());
        Thread thread3 = new Thread(futureTask);
        thread3.start();
        System.out.println(futureTask.get());
    }
}

測試結果:

new thread by lambda implement runnable interface

new thread by implement runnable interface

new thread by extend thread and override run method

new thread by implement callable interface

call method return finished

 

依賴於線程池的創建方式:

package concurrent.newThread;

import java.util.concurrent.*;

public class NewThreadByExecutorPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //1 無返回值,傳入Runnable接口的lambda表達式實現
        executorService.submit(()->{
            System.out.println("new thread by lambda implement runnable interface");
        });

        //1.1 無返回值 傳入Runnable接口的實現類NewThreadImplementRunnable, 注意該類並不是線程類
        class NewThreadImplementRunnable implements Runnable {
            @Override
            public void run() {
                System.out.println("new thread by class implement runnable interface");
            }
        }
        executorService.submit(new NewThreadImplementRunnable());


        //2.1 有返回值,通過線程池,傳入實現callable接口的lambda表達式
        Future<String>  future = executorService.submit(()->{
            System.out.println("new thread by executorService and lambda implement callable method");
            return "second: call method return finished";
        });
        System.out.println(future.get());

        //2.2 有返回值,通過線程池,傳入Callable的實現類
        class ImplementCallable1 implements Callable<String> {
            @Override
            public String call() throws Exception {
                System.out.println("new thread by executorService and class implement callable");
                return "first: call method return finished";
            }
        }
        future = executorService.submit(new ImplementCallable1());
        System.out.println(future.get());
    }
}

測試結果:

new thread by lambda implement runnable interface

new thread by class implement runnable interface

new thread by executorService and lambda implement callable method

second: call method return finished

new thread by executorService and class implement callable

first: call method return finished

獲取線程結果的方式:

第一種方式是往線程池傳入一個callabe接口,通過future獲取返回的結果;

第二種方式是往thread傳入一個FutureTask, 通過FutureTask的get方法獲取結果

第三種方式通過利用執行CompletableFuture的異步方法,通過CompletableFuture的get方法獲取結果。

 

public class ThreadReturnValue {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService  = Executors.newFixedThreadPool(2);
        Future<String> future = executorService.submit(()-> {
            System.out.println("begin to do logic work");
            return "get result by future\n";
        });
        System.out.println(future.get());


        FutureTask<String> futureTask = new FutureTask<String>(()->{
            System.out.println("begin to do logic work");
            return "get result by futureTask\n";
        });
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
        
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(()->{
            System.out.println("begin to do logic work");
            return "get result by completableFuture\n";
        });
        System.out.println(future1.get());
    }
}

begin to do logic work

get result by future

begin to do logic work

get result by futureTask

begin to do logic work

get result by completableFuture

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM