Java multi-threading (XIII): Thread Pool

Thread pool class structure


1.Executor is the top-level interface, there is an execute method.
2.ExecutorService interface provides a way to manage threads.
3.AbstractExecutorService common thread management, SchedulerExecutorService manage scheduled tasks.

Simple example

public class MyThread46 {
    public static void main(String[] args)
    {
        long startTime = System.currentTimeMillis();
        final List<Integer> l = new LinkedList<Integer>();
        ThreadPoolExecutor tp = new ThreadPoolExecutor(100, 100, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(20000));
        final Random random = new Random();
        for (int i = 0; i < 20000; i++)
        {
            tp.execute(new Runnable()
            {
                public void run()
                {
                    l.add(random.nextInt());
                }
            });
        }
        tp.shutdown();
        try
        {
            tp.awaitTermination(1, TimeUnit.DAYS);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - startTime);
        System.out.println(l.size());
    }
}

Results are as follows

52
19919

ThreadPoolExecutor seven parameters

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)

1.corePoolSize
thread pool of the current number of threads that can exist
2.maximumPoolSize
thread pool to allow the maximum number of threads
3.keepAliveTime
when the number of threads is greater than corePoolSize will work, most spare time in front of the thread terminated.
4.unit
keepAliveTime time unit
5.workQueue
task store unexecuted
6.threadFactory
Executor factory to use when creating a new thread
7.handler
use handler when execution is blocked

CorePoolSize relationship with the maximumPoolSize

1. The number of threads in the pool is less than corePoolSize, new tasks are queued but directly add a new thread.
2. The number of threads in the pool greater than or equal corePoolSize, workQueue full, the new task is added workQueue rather than adding a new thread.
3. The number of threads in the pool or greater corePoolSize, workQueue full, but less than the number of threads maximumPoolSize, add a new thread to process the task is added.
4. The number of threads in the pool or greater corePoolSize, workQueue is full, and the number of threads greater than or equal maximumPoolSize, the new task is rejected, processing tasks using the handler rejected.

Executors

1.newSingleThreadExecutos () single-threaded thread pool

    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }

The new task to the queue, workQueue LinkedBlockingQueue unbounded queue using
the following sample code

public class MyThread47{
    static ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {
        for(int i =0;i<10;i++) {
            final int index = i;
            singleThreadExecutor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println(index);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        }

}

Results are as follows

0
1
2
3
4
5
6
7
8
9

2.newFixedThreadPool (int nThreads) fixed-size thread pool

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

Fixed size and single-threaded thread pool thread pool Similarly, the number of threads can manually specify
the following sample code

public class MyThread48 {
    public static void main(String[] args) {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int index = i;

            fixedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        System.out.println(index);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

Results are as follows

0
1
2
3
4
5
6
8
7
9

3.newCachedThreadPool () unbounded thread pool

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

How many tasks to be executed directly, the thread pool maximum number Integer.MAX_VALUE, 60s automatic recovery of idle threads.
The following sample code

public class MyThread49 {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            cachedThreadPool.execute(new Runnable() {

                @Override
                public void run() {
                    System.out.println(index);
                }
            });
        }
    }
}

Results are as follows

0
1
2
3
4
5
6
7
8
9

Guess you like

Origin www.cnblogs.com/Java-Starter/p/11525301.html