码迷,mamicode.com
首页 > 移动开发 > 详细

Android(Java)线程池:ExecutorService和Executors使用(二)

时间:2016-04-19 09:56:45      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

一、固定大小的线程池,newFixedThreadPool:

package Executor.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        doExecutor();
    }

    static void doExecutor()
    {
        //create reuse,fix number,thread pool
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //create threads
        Thread t1 = new Thread(new MyThread());
        Thread t2 = new Thread(new MyThread());
        Thread t3 = new Thread(new MyThread());
        Thread t4 = new Thread(new MyThread());
        Thread t5 = new Thread(new MyThread());
        //execute thread in thread pool
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        //shutdown thread pool
        pool.shutdown();
    }
    
    static class MyThread implements Runnable
    {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("running thread:"+Thread.currentThread().getName());
        }
    }
}
执行结果:

running thread:pool-1-thread-1
running thread:pool-1-thread-3
running thread:pool-1-thread-5
running thread:pool-1-thread-2
running thread:pool-1-thread-4

改变线程池的大小:

ExecutorService pool = Executors.newFixedThreadPool(3)

执行结果:

running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-2
running thread:pool-1-thread-3

结论:从以上结果可以看出,newFixedThreadPool的参数指定了可以运行的线程的最大数目,超过这个数目的线程加进去以后,不会运行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。

 二、单任务线程池,newSingleThreadExecutor:

ExecutorService pool = Executors.newSingleThreadExecutor();

running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1

参考:Android的ExecutorService线程池

Android(Java)线程池:ExecutorService和Executors使用(二)

标签:

原文地址:http://www.cnblogs.com/Android9527/p/5406957.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!