java 获取子线程_Java 主线程获取子线程返回结果

1.自定义

package com.jgyang.com;

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;

}

}

}

返回结果为:

8b0e22e1323a786ecc5b10fe0a10c6f6.png

2.使用FutureTask+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();

FutureTaskfutureTask = new FutureTask(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{

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";

}

}

}

返回结果为:

25533fd5faa473ff24c02dcf64050dfa.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值