新しいスレッドを開く第3の方法:Callable
import java.util.concurrent.Callable;
/**
*
* @copyright:**
* @project: **
* @author: pake35<[email protected]>
* @createDate: 2016-2-23
*/
public class ThreadC implements Callable<String>{
//
@Override
public String call() throws Exception {
try {
Thread.sleep(500L);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(" C");
return "Thread C";
}
}
スレッドクラスの定義
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* Callable
* @copyright:**
* @project:**
* @author: pake35<[email protected]>
* @createDate: 2016-2-23
*/
public class ThreadMain1 {
public static void main(String[] args) {
ThreadC c= new ThreadC();
FutureTask<String> futureTask = new FutureTask<String>(c);
new Thread(futureTask).start();
System.out.println(" begin!");
try {
System.out.println(" "+ futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(" end!");
}
}
結果を返します.
begin!
C
Thread C
end!