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";
}
}
}
返回结果为: