java最实用newFixedThreadPool线程池

##代码示例

  • MyTest.java
package myUtil.myUtil;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * 自我感觉最实用的线程,固定长度线程池总结
 *以及优点
 */
public class MyTest{  
	private static final Logger logger = LoggerFactory
			.getLogger(MyTest.class);
	
    public static void main(String[] argv){  
    	//创建线程本地变量
    	ThreadLocal threadLocal = new ThreadLocal();
    	/*创建可用线程数量的固定线程池*/
    	ExecutorService executorService =  Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
		executorService.execute(new Runnable() {//向线程池中添加线程
			@Override
			public void run() {//一定要捕获子线程异常,不然它出轨了都不知道
				try {
				
				} catch (Exception e) {
				
				}
			}
		});
		executorService.shutdown();//一定要调用这个方法,不然executorService.isTerminated()永远不为true
        while(true){//等待所有任务都结束了继续执行
            try {
                if(executorService.isTerminated()){
                    System.out.println("所有的子线程都结束了!");
                    break;
                }
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
	}  
}  

你可能感兴趣的:(j2ee功能封装,java)