創(chuàng)建線程3--實(shí)現(xiàn)Callable接口

2019-07-07 23:44 更新

注意:

1.實(shí)現(xiàn)Runnable接口創(chuàng)建線程沒有直接的返回值,但可以通過額外添加成員變量和get方法實(shí)現(xiàn)同樣的效果。
2.如果run方法內(nèi)有異常不能拋出,要在內(nèi)部直接抓取。

1.實(shí)現(xiàn)Callable接口創(chuàng)建線程的簡單實(shí)現(xiàn):

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;


public class MyThread {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //創(chuàng)建線程
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Race tortoise = new Race();
        //獲取值
        Future<Integer> future = executorService.submit(tortoise);
        int sum = future.get();
        System.out.println(sum);

        
        executorService.shutdown();
    }
}
class Race implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        // TODO Auto-generated method stub
        return 1000;
    }
}

2.實(shí)現(xiàn)Callable接口創(chuàng)建線程的復(fù)雜實(shí)現(xiàn):

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;


public class MyThread {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        //創(chuàng)建線程
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Race tortoise = new Race("烏龜", 1000);
        Race rabbit = new Race("兔子", 500);
        //獲取值
        Future<Integer> tortoiseFuture = executorService.submit(tortoise);
        Future<Integer> rabbitFuture = executorService.submit(rabbit);

        
        Thread.sleep(2000);//2秒
        tortoise.setFlag(false);//停止線程體循環(huán)
        rabbit.setFlag(false);

        
        int tortoiseSum = tortoiseFuture.get();
        int rabbitSum = rabbitFuture.get();
        System.out.println("烏龜跑了:" + tortoiseSum + "步。");
        System.out.println("兔子跑了:" + rabbitSum + "步。");

        
        executorService.shutdown();
    }
}
class Race implements Callable<Integer>{
    private String name;//名稱
    private long time;//延遲時(shí)間
    private boolean flag = true;//是否繼續(xù)走
    private int step;//步

    
    public Race(String name, long time) {
        this.name = name;
        this.time = time;
    }

    
    public void setFlag(boolean flag) {
        this.flag = flag;
    }


    @Override
    public Integer call() throws Exception {
        // TODO Auto-generated method stub
        while(flag) {
            Thread.sleep(time);//延遲
            step++;
        }
        return step;
    }
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號