Android(Java)线程池:ExecutorService和Executors使用(二)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Android(Java)线程池:ExecutorService和Executors使用(二),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1804字,纯文字阅读大概需要3分钟。
内容图文
![Android(Java)线程池:ExecutorService和Executors使用(二)](/upload/InfoBanner/zyjiaocheng/1230/376e6cd6670a4ef29c8b08fcd9bbf3f3.jpg)
一、固定大小的线程池,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(); } staticclass MyThread implements Runnable { @Override publicvoid 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
原文:http://www.cnblogs.com/Android9527/p/5406957.html
内容总结
以上是互联网集市为您收集整理的Android(Java)线程池:ExecutorService和Executors使用(二)全部内容,希望文章能够帮你解决Android(Java)线程池:ExecutorService和Executors使用(二)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。