如何实现主线程打印子线程的结果(阿里一面)
1.自定义runnable接口实现类
public class MySyncThreadTest {
public static void main(String[] args) throws Exception {
CustomRunnable cRunnacle = new CustomRunnable();
Thread thread = new Thread(cRunnacle,"子线程");
thread.start(); //子线程执行
System.out.println("主线程做自己的事情");
thread.join(); //等待子线程执行完毕,这里会阻塞
System.out.println("获取子线程返回结果:"+cRunnacle.getData());
}
static final class CustomRunnable implements Runnable{
private String a = "";
public void run() {
try {
System.out.println(Thread.currentThread().getName()+":执行 start");
Thread.sleep(2000); //子线程停留2秒
System.out.println(Thread.currentThread().getName()+":执行 end");
} catch (InterruptedException e) {
e.printStackTrace();
}
a = "Hello world";
}
private String getData() {
return a;
}
}
}
runnable接口的run方法是没有返回值的,因此可以自定义一个方法返回run方法运行的结果
2.Future实现类+Callable
package com.jgyang.com;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class MySyncThreadTest2 {
public static void main(String[] args) throws Exception {
CustomCallable cRunnacle = new CustomCallable();
FutureTask<String> futureTask = new FutureTask<String>(cRunnacle);
Thread thread = new Thread(futureTask,"子线程");
thread.start(); //子线程执行
System.out.println("主线程做自己的事情--start");
System.out.println("获取子线程返回结果:"+futureTask.get());//获取返回结果是会阻塞
System.out.println("主线程做自己的事情--end");
}
static final class CustomCallable implements Callable<String>{
public String call() throws Exception {
System.out.println(Thread.currentThread().getName()+":执行 start");
Thread.sleep(2000); //子线程停留2秒
System.out.println(Thread.currentThread().getName()+":执行 end");
return "Hello world";
}
}
}
我有一壶酒
足以慰风尘
尽倾江海里
赠饮天下人
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
2021-03-19 Springboot常用注解(复习用)