如何給run方法傳參?
(1)構造函數傳參
(2) 成員變量傳參
(3) 回調函數傳參
如何實現處理線程的返回值?
(1)主線程等待法
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 data now";
}
public static void main(String[] args) throws InterruptedException {
CycleWait cycleWait=new CycleWait();
//給方法附上多線程的屬性。
Thread thread =new Thread(cycleWait);
thread.start();
//cycleWait.value主線程執行到這裏的時候有可能子線程還沒有獲取到值,所以需要在值爲空的時候,讓主線程等待。
int i=0;
while (cycleWait.value==null){
//主線程等待法
Thread.currentThread().sleep(100);
i++;
System.out.println(i);
}
System.out.println("value="+cycleWait.value);
}
}
運行發現需要循環50次即主線程等待50個100毫秒才能取到值,而如果最後一次主線程取到值了,但是主線程還在等待,會有資源佔用等其他問題。
(2)使用Thread類的join()方法,阻塞當前線程以等待子線程處理完畢
public static void main(String[] args) throws InterruptedException {
CycleWait cycleWait=new CycleWait();
Thread thread =new Thread(cycleWait);
thread.start();
int i=0;
//join阻塞法
thread.join();
System.out.println("value="+cycleWait.value);
}
通過callable接口實現:通過FutureTask 或者線程池獲取
需要jdk是1.5以上。
public class MyCallable implements Callable {
@Override
public Object call() throws Exception {
String value ="test";
System.out.println("work ready to work");
Thread.currentThread().sleep(5000);
System.out.println("task done");
return value;
}
}
調用時
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("FutureTask is not done ,please wait!");
}
System.out.println("value = "+futureTask.get());
}
線程池:
public class ThreadPoolDemo {
public static void main(String[] args) {
//線程池提交 mycallable的任務。
ExecutorService executorService = Executors.newCachedThreadPool();
//向線程池提交
Future future = executorService.submit(new MyCallable());
Future future1 =executorService.submit(new MyCallable());
if(!future.isDone()){
System.out.println("task has not finished,please wait");
}
try {
System.out.println("value ="+future.get());
System.out.println("value ="+future1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally {
//結束線程池
executorService.shutdown();
}
}
}