JAvaスレッドプールタイムアウト中断
1534 ワード
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//ExecutorService exec = Executors.newCachedThreadPool();
ExecutorService exec = Executors.newFixedThreadPool(2);
Future<String> f = exec.submit(new TimeTask());
Future<String> f2 = exec.submit(new TimeTask2());
try {
f.get(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
f.cancel(true);
//
System.out.println("thread time out");
e.printStackTrace();
}
System.out.println("sfadsfasdfasdfasdfasdfasfd");
try {
f2.get(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
f.cancel(true);
//
System.out.println("thread time out");
e.printStackTrace();
}
}
}
時には途切れない