java 线程池


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


public class ThreadTest {
    

    /*
     * 单线程化的线程池,它只会用唯一的工作线程来执行任务,
     * 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行
     */
    static ExecutorService executor1 = Executors.newSingleThreadExecutor(); 
    
    //定长线程池,支持定时及周期性任务执行。 
    static ExecutorService executor2 = Executors.newScheduledThreadPool(3); 
    
    //定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
    static ExecutorService executor3 = Executors.newFixedThreadPool(3); 
    
    /*
     * 可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,
     * 若无可回收,则新建线程。 
     */
    static ExecutorService executor = Executors.newCachedThreadPool(); 
    public static void main  (String[] args) {

        System.out.println(executor);
        
        long a = System.currentTimeMillis();
//        executor.shutdown();
        for (int i = 0; i < 10; i++) {
            executor.execute(new Runnable() {
                
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }

        System.out.println(executor);
        

        System.out.println("总时间:"+ (System.currentTimeMillis()-a));
        
        
        
    }
    


   

}

 

你可能感兴趣的:(java)