u012636086的专栏

什么是线程池 ?

使劲电我,充电

AsyncTask实现线程池方法:列举三种常用

/** 每次只执行一个任务的线程池 */private static ExecutorService singleTaskExecutor = Executors.newSingleThreadExecutor();// 每次只执行一个线程任务的线程池/** 每次执行限定个数个任务的线程池 */private static ExecutorService limitedTaskExecutor = Executors.newFixedThreadPool(3);// 限制线程池大小为3的线程池/** 所有任务都一次性开始的线程池 */private static ExecutorService allTaskExecutor = Executors.newCachedThreadPool(); // 一个没有限制最大线程数的线程池创建不同的线程池服务,创建task AsyncTask task = new AsyncTask();添加到线程池,一行代码 task.executeOnExecutor(limitedTaskExecutor);整个 添加线程池的操作已经完成。

常见问题,

1,如何取消 stop Task?

分两种情况,,

(1), 如果线程还未run,直接调用

task.cancel(true); (2), 如果线程已经run起来,执行到doInBackground中,此时调用task.cancel(true)一般情况下是无效。此时需要通过标记位,跳出循环,结束线程 protected Object doInBackground(Object… x) {while (/* condition */) {// work…if (isCancelled()) break;}return null; } task调用cancel()一般情况下无效的原因如下,java Thread interruptdoc

interruptpublic void interrupt()Interrupts this thread.Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.If none of the previous conditions hold then this thread's interrupt status will be set.Interrupting a thread that is not alive need not have any effect.Throws:SecurityException – if the current thread cannot modify this thread

换而言之,如果线程走在wait(),join(),sleep(),io数据流操作,调用该方法会抛出异常,这时候捕获异常,也可以终止Thread。

2,如何暂停task?而不是取消task,如上传操作,暂停后可以继续开始,实现思路在stop的基础上再来层循环while(false == finished) {while(true == paused) { // 暂停下载Thread.sleep(500);}….}

这一秒不放弃,下一秒就会有希望。

u012636086的专栏

相关文章:

你感兴趣的文章:

标签云: