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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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);
    }
}

运行结果:

1
we have data now

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 或者 线程池获取

 1、future task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
MyCallable.class
 
package com.test.thread;
 
import java.util.concurrent.Callable;
// 实现callable接口
public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        String value = "test";
        System.out.println("ready to work");
        Thread.sleep(5000);
        System.out.println("task done");
        return value;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
FutureTaskDemo.class:
package com.test.thread;
 
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
 
//future task
public class FutureTaskDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> task = new FutureTask<String>(new MyCallable());
        new Thread(task).start();
        if (!task.isDone()) {
            System.out.println("task has not finished, please wait!");
        }
        System.out.println("task return:" + task.get());
    }
}

2、线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
TreadPoolDemo.class:
package com.test.thread;
 
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class TreadPoolDemo {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executorService =
                Executors.newCachedThreadPool();
        // 向线程池中提交任务
        Future<String> future = executorService.submit(new MyCallable());
        // 判断任务是否完成
        if (!future.isDone()) {
            System.out.println("task not finished, please wait~~");
        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 将线程池关闭
            executorService.shutdown();
        }
    }
}

  

 

posted @   豆芽花花儿酱  阅读(4960)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示