JAVA中线程池的简单使用
比如现在有10个线程,但每次只想运行3个线程,当这3个线程中的任何一个运行完后,第4个线程接着补上。这种情况可以使用线程池来解决,线程池用起来也相当的简单,不信,你看:
package com.demo; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPool { private int threadCount = 10; private int threadpoolCount = 3; public void threadPoolControl() { ThreadObject[] et = new ThreadObject[threadCount]; ExecutorService service = Executors.newFixedThreadPool(threadpoolCount); Collection<ThreadObject> c = new ArrayList<ThreadObject>(); for (int i = 0; i < threadCount; i++) { et[i] = new ThreadObject(); c.add(et[i]); } try { service.invokeAll(c); service.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
再加上ThreadObject类,这个类主要是线程的具体实现方法:
package com.demo; import java.util.concurrent.Callable; public class ThreadObject implements Callable<Object>{ public Object call() throws Exception { //do something...... return null; } }
点亮测试人生!QQ:408129370
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号:
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号: