java 다중 루틴 실행 방법의 ThreadPoolExecutor와 Executors 비교

8583 단어 다중 스레드
Executors       :
  • newFixedThreadPool() 방법: 고정된 수량의 스레드 탱크가 있고 스레드 수량은 시종 변하지 않습니다.새 작업이 제출되었을 때, 라인에 빈 프로세스가 있으면 그것을 실행합니다.없으면 새 작업이 작업 대기열에서 일시 중지됩니다.소스: 아래
    /**
         * Creates a thread pool that reuses a fixed number of threads
         * operating off a shared unbounded queue.  At any point, at most
         * nThreads threads will be active processing tasks.
         * If additional tasks are submitted when all threads are active,
         * they will wait in the queue until a thread is available.
         * If any thread terminates due to a failure during execution
         * prior to shutdown, a new one will take its place if needed to
         * execute subsequent tasks.  The threads in the pool will exist
         * until it is explicitly {@link ExecutorService#shutdown shutdown}.
         *
         * @param nThreads the number of threads in the pool
         * @return the newly created thread pool
         * @throws IllegalArgumentException if {@code nThreads <= 0}
         */
        public static ExecutorService newFixedThreadPool(int nThreads) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                          0L, TimeUnit.MILLISECONDS,
                                          new LinkedBlockingQueue());
        }
  • newCachedThreadPool () 방법: 라인의 수량이 고정되지 않아 라인이 부족할 때 새로운 라인이 생성됩니다.
    /**
         * Creates a thread pool that creates new threads as needed, but
         * will reuse previously constructed threads when they are
         * available, and uses the provided
         * ThreadFactory to create new threads when needed.
         * @param threadFactory the factory to use when creating new threads
         * @return the newly created thread pool
         * @throws NullPointerException if threadFactory is null
         */
        public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
            return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                          60L, TimeUnit.SECONDS,
                                          new SynchronousQueue(),
                                          threadFactory);
        }
     
  • newSingleThreadExecutor () 방법: 하나의 라인만 있는 라인 풀로 먼저 나온 순서대로 대기열의 작업을 수행합니다.
    /**
         * Creates a single-threaded executor that can schedule commands
         * to run after a given delay, or to execute periodically.
         * (Note however that if this single
         * thread terminates due to a failure during execution prior to
         * shutdown, a new one will take its place if needed to execute
         * subsequent tasks.)  Tasks are guaranteed to execute
         * sequentially, and no more than one task will be active at any
         * given time. Unlike the otherwise equivalent
         * newScheduledThreadPool(1) the returned executor is
         * guaranteed not to be reconfigurable to use additional threads.
         * @return the newly created scheduled executor
         */
        public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
            return new DelegatedScheduledExecutorService
                (new ScheduledThreadPoolExecutor(1));
        }
     
  • newSingleThreadScheduledExecutor () 방법: 하나의 스레드만 있는 스레드 탱크이지만 실행 시간이나 실행 주기를 지정할 수 있습니다
    /**
         * Creates a single-threaded executor that can schedule commands
         * to run after a given delay, or to execute periodically.  (Note
         * however that if this single thread terminates due to a failure
         * during execution prior to shutdown, a new one will take its
         * place if needed to execute subsequent tasks.)  Tasks are
         * guaranteed to execute sequentially, and no more than one task
         * will be active at any given time. Unlike the otherwise
         * equivalent newScheduledThreadPool(1, threadFactory)
         * the returned executor is guaranteed not to be reconfigurable to
         * use additional threads.
         * @param threadFactory the factory to use when creating new
         * threads
         * @return a newly created scheduled executor
         * @throws NullPointerException if threadFactory is null
         */
        public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
            return new DelegatedScheduledExecutorService
                (new ScheduledThreadPoolExecutor(1, threadFactory));
        }
  • 그들의 원본을 보면 알 수 있듯이,
    newCachedThreadPool newFixedThreadPool       ThreadPoolExecutor       maximumPoolSize、keepAliveTimeunit,workQueue、threadFactory        。

    만약 우리가 ThreadPoolExecutor 방법을 직접 호출한다면 이 값들은 스스로 정의할 수 있다
    /**
         * Creates a new {@code ThreadPoolExecutor} with the given initial
         * parameters and default rejected execution handler.
         *
         * @param corePoolSize the number of threads to keep in the pool, even
         *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
         * @param maximumPoolSize the maximum number of threads to allow in the
         *        pool
         * @param keepAliveTime when the number of threads is greater than
         *        the core, this is the maximum time that excess idle threads
         *        will wait for new tasks before terminating.
         * @param unit the time unit for the {@code keepAliveTime} argument
         * @param workQueue the queue to use for holding tasks before they are
         *        executed.  This queue will hold only the {@code Runnable}
         *        tasks submitted by the {@code execute} method.
         * @param threadFactory the factory to use when the executor
         *        creates a new thread
         * @throws IllegalArgumentException if one of the following holds:
    * {@code corePoolSize < 0}
    * {@code keepAliveTime < 0}
    * {@code maximumPoolSize <= 0}
    * {@code maximumPoolSize < corePoolSize} * @throws NullPointerException if {@code workQueue} * or {@code threadFactory} is null */ public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); }

    ThreadPoolExecutor 소스입니다.
    다음은 우리가 예를 하나 써서 효과를 봅시다.
    public class MyThreadTest implements Runnable,Comparable{
    
    
        private static ExecutorService executorService=Executors.newFixedThreadPool(100);
    
        private static Executor myThread=new ThreadPoolExecutor(100,100,0L, TimeUnit.SECONDS,new PriorityBlockingQueue());
        private String name;
        public MyThreadTest(String name){
            this.name=name;
        }
        public MyThreadTest(){
            name="";
        }
    
        @Override
        public void run(){
            try{
                Thread.sleep(100);
                System.out.println(name+" running....");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        @Override
        public int compareTo(MyThreadTest o){
            int me = Integer.valueOf(name.split("_")[1]);
            int other = Integer.valueOf(o.name.split("_")[1]);
            return me-other;
        }
    
    
        public static void main(String[] args) {
            for (int i=0;i<1000;i++){
    //            myThread.execute(new MyThreadTest("test_"+(i)));
    
                executorService.execute(new MyThreadTest("test_"+(i)));
    
            }
        }
    }
    
    test_56 running....
    test_39 running....
    test_37 running....
    test_43 running....
    test_57 running....
    test_42 running....
    test_33 running....
    test_15 running....
    test_97 running....
    test_1 running....
    test_74 running....
    test_54 running....
    。。。
    。。。
    。。。
    test_948 running....
    test_943 running....
    test_942 running....
    test_940 running....
    test_941 running....
    test_929 running....
    test_934 running....
    test_932 running....
    test_926 running....
    test_925 running....
    test_923 running....

    양자의 집행 효율이 많지 않으므로 특별한 요구가 없으면 사용을 권장한다
    ExecutorService executorService=Executors.newFixedThreadPool(100);         。               
    Executor myThread=new ThreadPoolExecutor(100,100,0L, TimeUnit.SECONDS,new PriorityBlockingQueue());

    여기서 new Priority BlockingQueue()는 queue를 직접 정의할 수 있습니다.

    좋은 웹페이지 즐겨찾기