您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Java Executor执行器的饱和策略主要有以下几种:
RejectedExecutionException
异常。以下是如何使用这些饱和策略的示例代码:
import java.util.concurrent.*;
public class ExecutorServiceExample {
public static void main(String[] args) {
// 创建一个容量为2的队列
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(2);
// 使用默认的AbortPolicy
ThreadPoolExecutor executor1 = new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS, queue,
new ThreadPoolExecutor.AbortPolicy());
// 使用CallerRunsPolicy
ThreadPoolExecutor executor2 = new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS, queue,
new ThreadPoolExecutor.CallerRunsPolicy());
// 使用DiscardPolicy
ThreadPoolExecutor executor3 = new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS, queue,
new ThreadPoolExecutor.DiscardPolicy());
// 使用DiscardOldestPolicy
ThreadPoolExecutor executor4 = new ThreadPoolExecutor(
1, 1, 0L, TimeUnit.MILLISECONDS, queue,
new ThreadPoolExecutor.DiscardOldestPolicy());
// 提交任务进行测试
for (int i = 0; i < 5; i++) {
final int taskNumber = i;
try {
executor1.submit(() -> {
System.out.println("Task " + taskNumber + " is running on thread " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
} catch (RejectedExecutionException e) {
System.out.println("Task " + taskNumber + " was rejected by AbortPolicy");
}
}
// 关闭执行器
executor1.shutdown();
executor2.shutdown();
executor3.shutdown();
executor4.shutdown();
}
}
选择合适的饱和策略取决于具体的应用场景和需求。例如,如果需要确保所有任务都能被执行,可以选择CallerRunsPolicy
;如果对任务丢失不敏感,可以选择DiscardPolicy
或DiscardOldestPolicy
。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。