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;
	}

		
	
}

 

posted on 2015-04-07 09:55  张飞_  阅读(3131)  评论(1编辑  收藏  举报

导航