小言_互联网的博客

java获取线程的返回值

311人阅读  评论(0)

可以通过三种方法获取子线程的返回值:

  • 主线程等待法,主线程一直等待到子线程完毕返回为止:比如说子线程需要5秒才能进行赋值,主线程开启子线程后,直接输出那个值得到的是null,那么我们要让主线程一直等(sleep)到子线程执行完再去输出那个值就有了,可以获取到该值。
public class Test implements Runnable{
    private String flag = null;
    public void run() {
        try{
            //为了试验设置等待1000 ms
            Thread.currentThread().sleep(1000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        flag = "response data";
    }

    public static void main(String[] args) {
        Test test = new Test();
        Thread t = new Thread(test);
        t.start();
        while (test.flag == null){
            //如果还是空的话继续等待100毫秒
            Thread.currentThread().sleep(100);
        }
        System.out.print("test:" + test.flag);
    }
}
  • 使用Thread类中的join(),它会阻塞调用子线程的主线程,知道子线程执行完毕为止。
public class TestJoin {
    static class JoinThread implements Runnable {

        @Override
        public void run() {
            for(int i=0; i<100; i++) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new JoinThread());;
        Thread thread2 = new Thread(new JoinThread());
        
        thread1.start();
        thread1.join();
        //等待thread1线程执行完再执行thread2线程任务
        thread2.start();
        
    }
}
  • 通过Callable接口实现:通过FutureTask或者线程池获取

实现Callable接口:

public class TestCallable implements Callable<String> {
    @Override
    public String call() throws Exception{
        String responseData = "test";
        //过三秒返回值
        Thread.currentThread().sleep(3000);
        return responseData;
    }
}

FutureTask获取:

public class forTest{
    public static void main(String[] args) throws ExecutionException, InterruptedException{
        FutureTask<String> task = new FutureTask<String>(new TestCallable());
        new Thread(task).start();
        if(!task.isDone()){
            System.out.print("wait for task of thread. . .");
        }
        System.out.print("final return :" + task.get());
    }
}

 

转载请注明出处:https://blog.csdn.net/qq_36652619


转载:https://blog.csdn.net/qq_36652619/article/details/101767758
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场