1. 程式人生 > >我就吃瓜(Guava): 併發程式設計ListenableFuture

我就吃瓜(Guava): 併發程式設計ListenableFuture

ListenableFuture: 可以監聽的Future,繼承了Future。

  • Callable介面,與Runnable介面作用類似,但是可以設定返回值。

// 實現Callable介面
    class Task implements Callable<String> {

        private String ticket;
        public Task(String ticket) {
            this.ticket = ticket;
        }
        //重寫Call()方法
        @Override
        public String call() throws Exception {
            System.out.println("已賣" + ticket);
            return ticket;
        }
    }
  • FutureCallback介面,獲取非同步計算的結果,使用onSuccess()和onFailure()進行回撥
//實現FutureCallback介面
class MyFutureCallback implements FutureCallback<String> {
    @Override
    public void onSuccess(String str) {
        System.out.println(str + "成功了");
    }

    @Override
    public void onFailure(Throwable throwable) {

    }
}
  • 全部程式碼
public class ConcurrentDemo {
    public List<String> createTickets() {
        ArrayList<String> strings = new ArrayList<String>();
        for (int i = 0; i < 100; i++) {
            strings.add("ticket" + i);
        }
        return strings;
    }

    // 實現Callable介面
    class Task implements Callable<String> {

        private String ticket;

        public Task(String ticket) {
            this.ticket = ticket;
        }

        //重寫Call()方法
        @Override
        public String call() throws Exception {
            System.out.println("已賣" + ticket);
            return ticket;
        }
    }

    /**
     * 實現FutureCallback介面,獲取非同步計算的結果,使用onSuccess()
     * 和onFailure()回撥
     */
    class MyFutureCallback implements FutureCallback<String> {
        @Override
        public void onSuccess(String str) {
            System.out.println(str + "成功了");
        }

        @Override
        public void onFailure(Throwable throwable) {

        }
    }

    @Test
    public void sellTickets() {
        //產生車票
        List<String> tickets = createTickets();
       /* //建立執行緒池
        ExecutorService pool = new ThreadPoolExecutor(5, 10, 0L,TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());*/
        //執行緒池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        ListeningExecutorService service = MoreExecutors.listeningDecorator(pool);
        //初始化一個ListenableFuture的list
        ArrayList<ListenableFuture<String>> futures = Lists.newArrayList();
        for (int i = 0; i < tickets.size(); i++) {
            ListenableFuture<String> submit = service.submit(new Task(tickets.get(i)));
            //添加回調函式
            Futures.addCallback(submit, new MyFutureCallback());
            futures.add(submit);
        }
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            System.out.println(e);
        } finally {
            pool.shutdown();
            System.out.println("操作完畢");
        }
    }
}