(1)主线程等待法
package com.interview.thread;
//获取多线程返回值1:主线程等待
public class CycleWait implements Runnable{
private String value;
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value = "we have data now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait cw = new CycleWait();
Thread t1 = new Thread(cw);
t1.start();
while(cw.value == null) {
Thread.sleep(100);
}
System.out.println("value:" + cw.value);
}
}
(2)使用Thread的join阻塞当前线程等待
package com.interview.thread;
//获取多线程返回值1:主线程等待
public class CycleWait implements Runnable{
private String value;
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value = "we have data now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait cw = new CycleWait();
Thread t1 = new Thread(cw);
t1.start();
t1.join();
System.out.println("value:" + cw.value);
}
}
(3)通过Callable的FutureTask
package com.interview.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
if(!task.isDone()) {
System.out.println("任务未处理完成。。");
}
System.out.println("任务执行结果:" + task.get());
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
String value = "result value";
System.out.println("线程开始处理任务");
Thread.sleep(5000);
System.out.println("线程结束处理任务");
return value;
}
}
(4)通过Callable接口,线程池的Future实现
package com.interview.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newCachedThreadPool();
Future<String> future = pool.submit(new MyCallable());
if(!future.isDone()) {
System.out.println("等待任务...");
}
System.out.println("结果:" + future.get());
pool.shutdown();
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
String value = "result value";
System.out.println("线程开始处理任务");
Thread.sleep(5000);
System.out.println("线程结束处理任务");
return value;
}
}