现在的位置: 首页 > 综合 > 正文

Java——Runnable 和Callable

2018年04月12日 ⁄ 综合 ⁄ 共 2528字 ⁄ 字号 评论关闭

一般情况下,多线程的使用涉及到了Thread:一个类extends Thread, Override Thread中 的run方法即成为一个线程类。

public class RunnableTask extends Thread {
    private int num;
    public RunnableTask(int num){
        this.num = num;
    }
    @Override
    public void run() {
        int n = 10;
        while(n>0){
            System.out.println("running "+num);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            n--;
        }
    }
}

或者,原始类 implements Runnable接口,实现其run方法,也能成为线程类。

public class RunnableTask implements Runnable {
    private int num;
    public RunnableTask(int num){
        this.num = num;
    }
    @Override
    public void run() {
        int n = 10;
        while(n>0){
            System.out.println("running "+num);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            n--;
        }
    }
}

再或者,原始类 extends TimerTask 类,实现run方法。

public class RunnableTask extends TimerTask {
    private int num;
    public RunnableTask(int num){
        this.num = num;
    }

    @Override
    public void run() {
        int n = 10;
        while(n>0){
            System.out.println("running "+num);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            n--;
        }
    }
}

对于TimerTask的类,才能使用Timer进行调度执行。

public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
       Timer timer = new Timer();
        timer.schedule(new RunnableTask(3),2000);
    }
}

对于Runnable 和 Thread,可调用 ExecutorService 生成 Threadpool,执行这些线程类即可。

<pre name="code" class="java">public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
       ExecutorService pool = ThreadPool.getThreadPool(3);
        pool.submit(new RunnableTask(3));
        pool.submit(new RunnableTask(2));
    }
}

有时,在执行完线程池中的所有线程的时候需要返回一些东西或者紧接着处理一些东西,而仅仅在线程们全都执行完毕之后才能执行,则


需要使用Callable.
执行Callable的类之后会返回一个Future对象,该对象中存放着执行完该线程返回的东西。
顾名思义,Future的存在意义就是它能够作为一个预先的装置得到一个预先的结果(抽象上)。
如果需要在线程完毕之后才能进行一些功能,则可使用Future.get(),若该线程未执行完毕,则Future.get()会一直阻塞,直到执行完(或抛出异常)。
</pre><pre name="code" class="java">
<pre name="code" class="java">public class CallableTask implements Callable<Boolean> {
    private int num;
    public CallableTask(int num) throws NoSuchAlgorithmException {
        this.num = num;
    }
    @Override
    public Boolean call() throws Exception {
        int n = 5;
        while(n>0){
            System.out.println("running "+num);
            Thread.sleep(1000);
            n--;
        }
        return true;
    }
}

public class Test {
    public static void otherFunc(List<Future> resultList) throws ExecutionException, InterruptedException {

        Boolean rst = true;
        for(Future future:resultList){
            rst = (Boolean) future.get();
        }
        System.out.println("others");
    }


    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Future> resultList = new ArrayList<Future>();
        for(int i=0;i<5;i++){
            Future future = executorService.submit(new CallableTask(i));
            resultList.add(future);
        }
        otherFunc(resultList);
    }
}

使用Callable的时候想到一个需求,即能否使用类似Timer的计时器支持Callable的线程类?(基于频率的重复执行)


抱歉!评论已关闭.