加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java多线程-处理线程的返回值

发布时间:2020-12-15 01:59:09 所属栏目:Java 来源:网络整理
导读:一、主线程等待法:优点:实现简单,缺点:代码冗余 package com.test.thread;public class CycleWait implements Runnable { private String value; @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printS

一、主线程等待法:优点:实现简单,缺点:代码冗余

package com.test.thread;

public class CycleWait implements Runnable {
    private String value;

    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = "we have data now";
    }

    public static void main(String[] args) throws InterruptedException {
        CycleWait cycleWait = new CycleWait();
        Thread t = new Thread(cycleWait);
        t.start();
        while (cycleWait.value == null) {
            Thread.sleep(100);
        }
        System.out.println(cycleWait.value);
    }
}

运行结果:

we have data now

二、使用Thread类的join()阻塞当前线程,以等待子线程处理完毕。优点:比“主线程等待法”更简单 缺点:粒度更细

package com.test.thread;

public class CycleWait implements Runnable {
    private String value;

    @Override
    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        value = "we have data now";
    }

    public static void main(String[] args) throws InterruptedException {
        CycleWait cycleWait = new CycleWait();
        Thread t = new Thread(cycleWait);
        t.start();
       // join方法,在start后
        t.join();
        System.out.println(cycleWait.value);
    }
}
    

  

三、通过Callable接口实现:通过FutureTask 或者 线程池获取

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读