java 基础--<线程池>

1.接口 Executor


void execute(Runnable command)
在未来某个时间执行给定的命令。

2.接口 public interface ExecutorService extends Executor


submit(Runnable task)
提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
submit(Callable<T> task)
提交一个返回值的任务用于执行,返回一个表示任务的未决结果的 Future。
invokeAll(Collection<? extends Callable<T>> tasks)
执行给定的任务,当所有任务完成时,返回保持任务状态和结果的 Future 列表。
shutdown()
启动一次顺序关闭,执行以前提交的任务,但不接受新任务。
List<Runnable> shutdownNow()
试图停止所有正在执行的活动任务,暂停处理正在等待的任务,并返回等待执行的任务列表。


3.接口public interface ScheduledExecutorService extends ExecutorService

一个 ExecutorService,可安排在给定的延迟后运行或定期执行的命令。


4,抽象类public abstract class AbstractExecutorService implements ExecutorService

5.线程池的类 public class ThreadPoolExecutor extends AbstractExecutorService

核心和最大池大小
当新任务在方法 execute(java.lang.Runnable) 中提交时,
如果运行的线程少于 corePoolSize,则创建新线程来处理请求,即使其他辅助线程是空闲的。
如果运行的线程多于 corePoolSize 而少于 maximumPoolSize,则仅当队列满时才创建新线程(优先使用空闲线程,没有空闲线程才创建新线程)。
如果设置的 corePoolSize 和 maximumPoolSize 相同,则创建了固定大小的线程池。
如果将 maximumPoolSize 设置为基本的无界值(如 Integer.MAX_VALUE),则允许池适应任意数量的并发任务。

创建新线程
使用 ThreadFactory 创建新线程。如果没有另外说明,则在同一个 ThreadGroup 中一律使用 Executors.defaultThreadFactory() 创建线程,
并且这些线程具有相同的 NORM_PRIORITY 优先级和非守护进程状态。
通过提供不同的 ThreadFactory,可以改变线程的名称、线程组、优先级、守护进程状态,等等。
如果从 newThread 返回 null 时 ThreadFactory 未能创建线程,则执行程序将继续运行,但不能执行任何任务。

保持活动时间
如果池中当前有多于 corePoolSize 的线程,则这些多出的线程在空闲时间超过 keepAliveTime 时将会终止,这提供了当池处于非活动状态时减少资源消耗的方法。
使用 Long.MAX_VALUE TimeUnit.NANOSECONDS 的值在关闭前有效地从以前的终止状态禁用空闲线程。

方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)

用给定的初始参数和默认的线程工厂及被拒绝的执行处理程序创建新的 ThreadPoolExecutor。使用 Executors 工厂方法之一比使用此通用构造方法方便得多。

参数:
corePoolSize - 池中所保存的线程数,包括空闲线程。
maximumPoolSize - 池中允许的最大线程数。
keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
unit - keepAliveTime 参数的时间单位。
workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。

allowCoreThreadTimeOut(boolean value)
设置核心线程和非核心线程的任务超时时间,keepAliveTime时间。

shutDown
不在接受新的线程,并且等待之前提交的线程都执行完在关闭

shutDownNow
直接关闭活跃状态的所有的线程,并返回等待中的线程

6.public class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements ScheduledExecutorService

public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
达到给定的延时时间后,执行任务。这里传入的是实现Runnable接口的任务,因此通过ScheduledFuture.get()获取结果为null

public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);
达到给定的延时时间后,执行任务。这里传入的是实现Callable接口的任务,因此,返回的是任务的最终计算结果

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
是以上一个任务开始的时间计时,period时间过去后,检测上一个任务是否执行完毕,如果上一个任务执行完毕,则当前任务立即执行,如果上一个任务没有执行完毕,则需要等上一个任务执行完毕后立即执行

public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
当达到延时时间initialDelay后,任务开始执行。上一个任务执行结束后到下一次,任务执行,中间延时时间间隔为delay。以这种方式,周期性执行任务。


7 类 :Executors

static ExecutorService newFixedThreadPool(int nThreads)
//创建定长线程池(核心线程数与最大线程数一样)

static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们,并在需要时使用提供的 ThreadFactory 创建新线程。

static ExecutorService newSingleThreadExecutor()
创建单个线程的线程池(核心线程数与最大线程数都为1)

static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建定长线程池(定核心线程数为参数,最大线程数为int的最大值)


executorService= Executors.newCachedThreadPool();
//创建无限长线程池(核心线程数为0,最大线程数为int最大值)

public class ExecutorsTest {
    String TAG = "ExecutorsTest";

    //Callable 获取线程的返回值
     public void startThreadPool(){
         SumCallable sumCallable=new SumCallable();
         //创建定长线程池(定核心线程数为参数,最大线程数为int的最大值)
         ExecutorService executors=Executors.newCachedThreadPool();
         Future<Integer> future=  executors.submit(sumCallable);
         try {
             //future.get 是阻塞方法
             Log.e(TAG,"sum1="+ future.get());
         } catch (Exception e) {
             e.printStackTrace();
         }
     }

    //Runnable 没有返回值
    public void startThreadPool2(){
        SumRunnable sumCallable=new SumRunnable();
        //创建定长线程池(定核心线程数为参数,最大线程数为int的最大值)
        ExecutorService executors=Executors.newScheduledThreadPool(20);
        executors.submit(sumCallable);
    }

    //延时执行任务
    public void startThreadPool3(){
        SumRunnable sumCallable=new SumRunnable();
        //创建定长线程池(定核心线程数为参数,最大线程数为int的最大值)
        ScheduledExecutorService executors=Executors.newScheduledThreadPool(100);
        executors.schedule(sumCallable,3, TimeUnit.SECONDS);
        Log.e(TAG,"3秒钟之后执行");
    }

    //Runnable 没有返回值
    public void startThreadPool4(){
        SumRunnable sumCallable=new SumRunnable();
        //创建定长线程池(定核心线程数为参数,最大线程数为int的最大值)
        ExecutorService executors=Executors.newCachedThreadPool(new ThreadFactoryTest());
        executors.submit(sumCallable);
    }



    public class SumRunnable implements Runnable{
        @Override
        public void run() {
            Log.e(TAG,"开始执行");
            int sum=0;
            for(int k=0;k<100;k++){
                sum+=k;
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.e(TAG,"sum="+ sum);
        }
    }

    public class SumCallable implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            int sum=0;
            for(int k=0;k<100;k++){
                sum+=k;
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Log.e(TAG,"sum="+ sum);
            return sum;
        }
    }

    public class ThreadFactoryTest implements ThreadFactory{

        @Override
        public Thread newThread(Runnable r) {
            Log.e(TAG,"ThreadFactoryTest newThread");
              return  new Thread(r);
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/jtzp007/p/11448515.html