1,主线程等待法:
public class MainThreadWait implements Runnable{
private String value;
@SuppressWarnings("static-access")
@Override
public void run() {
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "test";
}
public static void main(String[] args) throws InterruptedException {
MainThreadWait mainThreadWait = new MainThreadWait();
Thread thread = new Thread(mainThreadWait);
thread.start();
//-----------------------------------------
while(null == mainThreadWait.value) {
Thread.currentThread().sleep(1000);
}
//-----------------------------------------
System.out.println("value = " + mainThreadWait.value);
}
}
2,使用Thread类的join方法阻塞此线程以等待此线程处理完毕
public class MainThreadWait implements Runnable{
private String value;
@SuppressWarnings("static-access")
@Override
public void run() {
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "test";
}
public static void main(String[] args) throws InterruptedException {
MainThreadWait mainThreadWait = new MainThreadWait();
Thread thread = new Thread(mainThreadWait);
thread.start();
// while(null == mainThreadWait.value) {
// Thread.currentThread().sleep(1000);
// }
//----------------------
thread.join();
//----------------------
System.out.println("value = " + mainThreadWait.value);
}
}
3,通过Callable接口实现(FutureTask)
public class MyCallable implements Callable<String>{
@SuppressWarnings("static-access")
@Override
public String call() throws Exception {
Thread.currentThread().sleep(5000);
return "test";
}
}
public class MyCallableMain {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<String> futureTask = new FutureTask<String>(new MyCallable());
new Thread(futureTask).start();
if (!futureTask.isDone()) {
System.out.println("还没有返回");
}
System.out.println(futureTask.get());
}
}
4,通过Callable接口实现(线程池)
public class ThreadPoolMain {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> task = executorService.submit(new MyCallable());
if (!task.isDone()) {
System.out.println("还没有返回");
}
try {
System.out.println(task.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}