前一段时间在调查Java 的TimeOut机制,现在附上程序
import
java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeOutExample {
public static void main(String[] args) throws Exception {
Callable reservationTask = new Callable() {
public String call() throws InterruptedException {
String s = "";
for (int i = 0; i < 5; i++) {
s += ".";
System.out.println(s);
Thread.sleep(1000);
}
return "task has runned";
}
};
final FutureTask future = new FutureTask(reservationTask);
Thread th = new Thread() {
public void run() {
future.run();
}
};
System.out.println("Start");
long start = new Date().getTime();
th.start();
try {
System.out.println(future.get(2, TimeUnit.SECONDS));
System.out.println("end");
} catch (TimeoutException e) {
System.out.println("time out");
future.cancel(true);
e.printStackTrace();
} finally {
long end = new Date().getTime();
System.out.println("total run time" + (end - start) + "millisecond");
}
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TimeOutExample {
public static void main(String[] args) throws Exception {
Callable reservationTask = new Callable() {
public String call() throws InterruptedException {
String s = "";
for (int i = 0; i < 5; i++) {
s += ".";
System.out.println(s);
Thread.sleep(1000);
}
return "task has runned";
}
};
final FutureTask future = new FutureTask(reservationTask);
Thread th = new Thread() {
public void run() {
future.run();
}
};
System.out.println("Start");
long start = new Date().getTime();
th.start();
try {
System.out.println(future.get(2, TimeUnit.SECONDS));
System.out.println("end");
} catch (TimeoutException e) {
System.out.println("time out");
future.cancel(true);
e.printStackTrace();
} finally {
long end = new Date().getTime();
System.out.println("total run time" + (end - start) + "millisecond");
}
}
}