首页 > 编程知识 正文

java executor,bindservice生命周期

时间:2023-05-03 14:42:02 阅读:51006 作者:3247

前言在我们的日常开发中,使用线程是不可避免的,有些还会使用多线程并发问题。 我们知道创建和释放线程需要大量的内存和资源。 如果每次需要使用线程时都新建一个Thread,则不可避免地会浪费资源。 此外,可以无限制地创建,如果发生冲突,则会消耗过多的系统资源,导致系统瘫痪。 由于不利于定时执行、定期执行、线程中断等扩展,因此需要理解ExecutorService的使用。

ExecutorService是Java提供的线程池。 这意味着每次需要使用线程时,都可以从ExecutorService中检索线程。 在有效控制最大并发线程数、提高系统资源利用率的同时,避免了过多的资源争用,避免了拥塞,同时提供了定时运行、定期运行、单线程、并发数控制等功能,无需使用TimerTask。

1.ExecutorService的创建方法publicthreadpoolexecutor (intcorepoolsize,int maximumPoolSize,long keepAliveTime,time unit,bll ThreadFactory threadFactory,rejectedexecutionhandlerhandler )所有线程池最终都是以这种方式创建的。

corePoolSize :核心线程数在创建后将不再释放。 如果创建的线程数未达到指定的核心线程数,则在达到最大核心线程数之前,将继续创建新的核心线程,核心线程数不会增加。 如果没有可用的核心线程,并且未达到最大线程数,则继续创建非核心线程。 如果核心线程数等于最大线程数,则在所有核心线程都处于活动状态时,任务将挂起并等待空闲线程执行。

maximumPoolSize :线程的最大数量,可以创建的线程的最大数量。 如果最大线程数等于核心线程数,则无法创建非核心线程;如果非核心线程空闲,则超过设置的空闲时间,将回收并释放正在使用的资源。

keepAliveTime :即线程空闲时可保存的最长时间。 超过此时间后,线程将被释放并销毁,但仅涵盖非核心线程。

unit :小时单位、TimeUnit.SECONDS等。

workQueue :任务队列。 存储暂时不能执行的任务,等待空闲线程执行任务。

threadFactory :线程项目,用于线程创建。

handler :用于在线程边界和队列容量达到最大时处理块的程序

2 .线程池类型2.1可缓存线程池executorservicecachepool=executors.newcachedthreadpool (让我们看看如何创建具体的:

publicstaticexecutorservicenewcachedthreadpool ((returnnewthreadpoolexecutor ) 0,Integer.MAX_VALUE,601,timeunit } ) 如果需要花费大量时间的工作,请不要应用创建方法。 这仅适用于生命周期短的任务。

2.2单线程池executorservicesinglepool=executors.newsinglethreadexecutor (; 做聪明的夕阳,也就是核心线程:

publicstaticexecutorservicenewsinglethreadexecutor ({ returnnewfinalizabledelegatedexecutorservice (newthreadpoolexecutor )

able>())); }

只用一个线程来执行任务,保证任务按FIFO顺序一个个执行。

2.3 固定线程数线程池 Executors.newFixedThreadPool(3); public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }

也就是创建固定数量的可复用的线程数,来执行任务。当线程数达到最大核心线程数,则加入队列等待有空闲线程时再执行。

2.4 固定线程数,支持定时和周期性任务 ExecutorService scheduledPool = Executors.newScheduledThreadPool(5); public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue());}

可用于替代handler.postDelay和Timer定时器等延时和周期性任务。

public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit); public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);

scheduleAtFixedRate和sheduleWithFixedDelay有什么不同呢?

scheduleAtFixedRate:创建并执行一个在给定初始延迟后的定期操作,也就是将在 initialDelay 后开始执行,然后在initialDelay+period 后下一个任务执行,接着在 initialDelay + 2 * period 后执行,依此类推 ,也就是只在第一次任务执行时有延时。

sheduleWithFixedDelay:创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟,即总时间是(initialDelay +  period)*n

2.4 手动创建线程池 private ExecutorService pool = new ThreadPoolExecutor(3, 10, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(512), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

可以根据自己的需求创建指定的核心线程数和总线程数。

3. 如何终止一个周期性任务呢?

直接上源码你就懂了:

public final class LgExecutorService { private ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<>(); private ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(5); private LgExecutorService() { } private static final class InnerExecutorService { private static final LgExecutorService INSTANCE = new LgExecutorService(); } public static LgExecutorService getInstance() { return InnerExecutorService.INSTANCE; } public ConcurrentHashMap<String, Future> getFutureMap() { return futureMap; } public void execute(Runnable runnable) { if (runnable != null) { executorService.execute(runnable); } } /** * @param runnable * @param delay 延迟时间 * @param timeUnit 时间单位 */ public void sheduler(Runnable runnable, long delay, TimeUnit timeUnit) { if (runnable != null) { executorService.schedule(runnable, delay, timeUnit); } } /** * 执行延时周期性任务 * * @param runnable {@code LgExecutorSercice.JobRunnable} * @param initialDelay 延迟时间 * @param period 周期时间 * @param timeUnit 时间单位 */ public <T extends JobRunnable> void sheduler(T runnable, long initialDelay, long period, TimeUnit timeUnit) { if (runnable != null) { Future future = executorService.scheduleAtFixedRate(runnable, initialDelay, period, timeUnit); futureMap.put(runnable.getJobId(), future); } } public static abstract class JobRunnable implements Runnable { private String jobId; public JobRunnable(@NonNull String jobId) { this.jobId = jobId; } /** * 强制终止定时线程 */ public void terminal() { try { Future future = LgExecutorService.getInstance().getFutureMap().remove(jobId); future.cancel(true); } finally { System.out.println("jobId " + jobId + " had cancel"); } } public String getJobId() { return jobId; } } }

自己写个demo测试后就知道结果了,还是自己动下手吧。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。