一、拒绝策略DiscardOldestPolicy
public class TestThreadPoolRejectDiscardOldestPolicy {
private final static ThreadPoolExecutor executorService = new ThreadPoolExecutor(
1,
1,
1L, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(1),
new ThreadPoolExecutor.DiscardOldestPolicy());
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
Future f1 = executorService.submit(() -> {
try {
System.out.println("f1 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future f2 = executorService.submit(() -> {
try {
System.out.println("f2 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future f3 = executorService.submit(() -> {
try {
System.out.println("f3 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.printf("f1=%s",f1.get());
System.out.printf("f2=%s",f2.get());
System.out.printf("f3=%s",f3.get());
System.out.println("================end================");
System.out.printf("f1=%s",f1.get(10,TimeUnit.SECONDS));
System.out.printf("f2=%s",f2.get(10,TimeUnit.SECONDS));
System.out.printf("f3=%s",f3.get(10,TimeUnit.SECONDS));
System.out.println("================end================");
}
}
二、拒绝策略DiscardPolicy
public class TestThreadPoolRejectDiscardPolicy {
private final static ThreadPoolExecutor executorService = new ThreadPoolExecutor(
1,
1,
1L, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(1),
new ThreadPoolExecutor.DiscardPolicy());
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
Future f1 = executorService.submit(() -> {
try {
System.out.println("f1 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future f2 = executorService.submit(() -> {
try {
System.out.println("f2 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future f3 = executorService.submit(() -> {
try {
System.out.println("f3 thread executing");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.printf("f1=%s",f1.get());
System.out.printf("f2=%s",f2.get());
System.out.printf("f3=%s",f3.get());
System.out.printf("f1=%s",f1.get(10,TimeUnit.SECONDS));
System.out.printf("f2=%s",f2.get(10,TimeUnit.SECONDS));
System.out.printf("f3=%s",f3.get(10,TimeUnit.SECONDS));
}
}