如何實現處理線程的返回值?
1、主線程等待法 缺點:需要自己實現循環等待的邏輯,當需要等待的變量較多時,代碼異常臃腫。
2、使用thread類的join()阻擋當前線程以等待子線程處理完畢。 缺點:控制力度不夠精細。
3、通過callable接口實現,通過FutureTask Or 線程池獲取。
一、那么,直接上代碼吧,我們首先開始第一種方法。先創建一個類CycleWait,如下所示:
public class CycleWait implements Runnable {
private String value;
@Override
public void run() {
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "we have date now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait wait = new CycleWait();
Thread thread = new Thread(wait);
thread.start();
//當值為null的時候一直循環,直到有值的時候才會返回。
//少了這一步,則可能取出為空的值。
while (wait.value == null) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(wait.value);
}
}
在循環到CycleWait執行完成時,會輸出結果 we have date now。
二、去掉循環體,使用join方法。給一返回結果一樣。
public class CycleWait implements Runnable {
private String value;
@Override
public void run() {
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "we have date now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait wait = new CycleWait();
Thread thread = new Thread(wait);
thread.start();
//當值為null的時候一直循環,直到有值的時候才會返回。
//少了這一步,則可能取出為空的值。
thread.join();
System.out.println(wait.value);
}
}
三、使用FutureTask獲得結果,進行控制。
public class myCallable implements Callable {
@Override
public String call() throws Exception {
String value = "test";
System.out.println("ready to work");
Thread.currentThread().sleep(5000);
System.out.println("task down");
return value;
}
}
public class FutureTaskDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> futureTask = new FutureTask<String>(new myCallable());
new Thread(futureTask).start();
if (!futureTask.isDone()) {
System.out.println("task has not ");
}
System.out.println("task reture:{}" + futureTask.get());
}
}
四、線程池的方式。好處:可以實現提交多個myCallable方法的線程,是線程池並發的去處理結果。
public class ThreadPoolDemo {
public static void main(String[] args) {
//創建線程池
ExecutorService executorService = Executors.newCachedThreadPool();
//提交myCallable的任務去執行
Future<String> future = executorService.submit(new myCallable());
if (!future.isDone()) {
System.out.println("task has not ");
}
try {
System.out.println("task reture:{}" + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
//關閉線程池
executorService.shutdown();
}
}
