Thread之四:java线程返回结果的方法

Thread之四:java线程返回结果的方法

Runnable、Callable、Future和FutureTask之一:获取线程的返回值

CompletionService之一:获得线程(线程池的)处理结果

 

本文目录:

第一种方法:通过线程的实例变量传递方式获取结果
第二种方法:使用Callable+FutureTask+Thread获取执行结果

 

获取线程的结果两种方式:一种继承Thread类实现;一种通过实现Callable接口。

第一种方法:通过线程的实例变量传递方式获取结果

因为实现Thread类的run方法自身是没有返回值的,所以不能直接获得线程的执行结果,但是可以通过在run方法里把最后的结果传递给实例变量,然后通过getXX方法获取该实例变量的值。继承实现的代码:

package com.dxz.thread;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class RunThread extends Thread {
    private String runLog = "";
    private String name;

    public RunThread(String name) {
        this.name = name;
    }

    public void run() {
        try {
            int time = new Random().nextInt(10);
            System.out.println("sleep "+ time +" second.");
            TimeUnit.SECONDS.sleep(time);
            this.runLog = this.name + time;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getRunLog() {
        return this.runLog;
    }
}
package com.dxz.thread;
public class RunThreadTest {

    public static void main(String[] args) throws InterruptedException {
        RunThread runT = new RunThread("world");
        runT.start();
        runT.join();
        System.out.println("result:="+runT.getRunLog());

    }

}

结果:

sleep 3 second.
result:=world3

结果2:

sleep 2 second.
result:=world2

第二种方法:使用Callable+FutureTask+Thread获取执行结果

继承Callable接口后需要实现call方法,而call方法默认是可以有返回值的,所以可以直接返回想返回的内容。接口的实现代码:

public class Test {
    public static void main(String[] args) {
        // 第一种方式
        /**
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();
        */
        // 第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread

        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        Thread thread = new Thread(futureTask);
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果" + futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }
}

class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for (int i = 0; i < 100; i++)
            sum += i;
        return sum;
    }
}

结果:

子线程在进行计算
主线程在执行任务
task运行结果4950
所有任务执行完毕

 

posted on 2015-12-17 11:05  duanxz  阅读(5515)  评论(0编辑  收藏  举报