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;
}
}
}
返回結果為:
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";
}
}
}
返回結果為:
總結
以上是生活随笔為你收集整理的java 获取子线程_Java 主线程获取子线程返回结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: laravel 异常捕获_Laravel
- 下一篇: python opencv2_Pytho