Java Concurrency: get the thread pool (in)

Submit jobs to the thread pool

1.1 execute()

    For submitting the task does not require a return value, it is impossible to determine whether the task is executed successfully thread pool. Input is a Runnable instance.

public void execute(Runnable command) { e.execute(command); }

    If there are no special requirements, use caching thread pool is the most appropriate;

    If you can only run one thread, you use a single thread pool;

    If you run a scheduled task, the on-demand or scheduled thread pool single thread pool;

    If there are no other special requirements, it can be used directly ThreadPoolExecutor class constructor to create a thread pool, and given himself seven parameters.

public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<Future<String>> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            //任务放到阻塞队列
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }

  

1.2 submit()

    For submitting the required return value of the task, the thread pool will return a Future type of object, the object can be determined whether the task is executed successfully, and () Returns a value obtained by get, get () will block the current thread know that the task is completed, and use get (long, unit) method will return immediately after the blocking period of time, the task may not have executed.

public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<Future<String>> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            //任务放到阻塞队列
            Future<String> f = executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    TimeUnit.SECONDS.sleep(2);
                    return Thread.currentThread().getName();
                }
            });
            list.add(f);
        }
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i).get()+"--------------"+i+"-------------------------");
        }
    }

Close the thread pool

    To close the thread pool thread pool by calling the shutdown or shutdownNow method.

    They are two principles traversing thread pool worker thread, and then one by one call interrupt method thread to thread the terminal, so the terminal can not respond to the task may never terminate.

    shutdownNow: First, the state of the thread pool is set to stop, and then try to stop all the threads being executed or suspend tasks, and returns a list of tasks awaiting execution.

    shutdown: only the state of the thread pool is set to shutdown state, then the middle of all the threads are not executing tasks.

    As long as the caller two close any one of the methods, isShutdown method returns true, when all the tasks closed, it indicates that the thread pool melon woman success, which is calling isTerminaed method returns true.

    Usually shutdown method to close the thread pool, if the task is not necessarily executed, you can call shutdownNow method.

    Use bounded queues, you can increase the stability and capacity of early warning systems.

Thread pool status

    1. When the thread pool is created, initially running state

    2. After the call shutdown method, in a shutdown state, the matter is no longer accepting new tasks, waiting for an existing job is finished

    3. shutdownNow execution method, enter the stop state, not to accept the new task, and try to terminate the task being performed

    4. When in shutdown or stop state, and all worker threads have been destroyed, the task queue is empty the cache, thread pool is set to terminated state.

     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED

    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

  

Guess you like

Origin www.cnblogs.com/dc-earl/p/11126825.html