Java並發工具類Future使用示例

前言

Future是一個接口類,定義瞭5個方法:

boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

通過這5個方法可以看出,Future不但可以獲取提交任務的執行結果,甚至還可以取消任務。

Future使用示例

摘自JDK中Future示例代碼

class ArchiveSearcherImpl implements ArchiveSearcher{

    @Override
    public String search(String target) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return target;
    }
}

interface ArchiveSearcher {
    String search(String target);
}

class App {

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.showSearch("search");
    }

    ExecutorService executor = Executors.newSingleThreadExecutor();
    ArchiveSearcher searcher = new ArchiveSearcherImpl();

    void showSearch(final String target)
            throws InterruptedException {
        // 提交任務
        Future<String> future
                = executor.submit(new Callable<String>() {
            public String call() {
                return searcher.search(target);
            }
        });
        displayOtherThings(); // do other things while searching
        try {
        	// 拿任務執行結果
            displayText(future.get()); // use future
        } catch (ExecutionException ex) {
            //cleanup();
            return;
        }
    }
    private void displayOtherThings() {
        System.out.println("do other things");
    }

    private void displayText(String s) {
        System.out.println(s);
    }
}

註意:future.get()方法是阻塞式的,如果調用該方法的時候任務尚未執行完成,則會一直等待下去,直到任務執行結束。

ExecutorService還有一個sumbit方法比較特殊:<T> Future<T> submit(Runnable task, T result);這個方法可以先把result這個參數傳給task使用,然後再通過get方法把result返回。

public class FutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        MyResult myResult = new MyResult();
        MyTask myTask = new MyTask(myResult);
		
		// 提交任務後,在任務中操作myResult
        Future<MyResult> future = executor.submit(myTask, myResult);
        // 最後get方法可以拿到myResult
        System.out.println(future.get());
    }

}


class MyTask implements Runnable {

    private MyResult myResult;

    public MyTask(MyResult myResult) {
        this.myResult = myResult;
    }

    @Override
    public void run() {
        myResult.setCode("10000");
    }
}

@Data
@ToString
class MyResult {
    private String code;
}

FutureTask

FutureTask是一個實現瞭Runnable和Future接口的工具類,結合瞭這兩個接口的能力,FutureTask即可以提交給線程任務執行,又可以獲取到執行結果。

具體代碼示例:

import java.util.concurrent.*;

public class FutureTaskTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask1 = new FutureTask<>(new MyTask1());
        FutureTask<String> futureTask2 = new FutureTask<>(new MyTask2());

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(futureTask1);
        executorService.submit(futureTask2);

        long start = System.currentTimeMillis();
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
        long end = System.currentTimeMillis();

        System.out.println(end - start);
    }

}

class MyTask2 implements Callable<String> {

    @Override
    public String call() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "MyTask2 over";
    }
}

class MyTask1 implements Callable<String> {

    @Override
    public String call() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "MyTask1 over";
    }
}

到此這篇關於Java並發工具類Future使用示例的文章就介紹到這瞭,更多相關Java並發工具類Future內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: