線程池的工作過程示例

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class DiscardPolicyDemo {  

    private static final int corePoolSize = 3;  
    private static final int maximumPoolSize = 6;  
    private static final int QueueCAPACITY = 10;  

    public static void main(String[] args) throws Exception {  

        // 創建線程池。線程池的"最大池大小"和"核心池大小"都爲1(THREADS_SIZE),"線程池"的阻塞隊列容量爲1(CAPACITY)。  
        ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QueueCAPACITY),new rejectedImpl());



        // 設置線程池的拒絕策略爲"丟棄"  

        // 新建10個任務,並將它們添加到線程池中。  
        for (int i = 0; i < 20; i++) {  
            Runnable myrun = new MyRunnable("task-"+i);  
            pool.execute(myrun);  
            
        }  
        // 關閉線程池  
        pool.shutdown();  
    }  
}

class rejectedImpl implements  RejectedExecutionHandler{

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
         System.out.println(String.format("Task %s rejected.", r.hashCode()));
        
    }
    
}
class MyRunnable implements Runnable {
    private String name;

    public MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        try {
            System.out.println(this.name + " is running.");
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

運行結果:

task-2 is running.
task-0 is running.
task-1 is running.
task-13 is running.
task-14 is running.
task-15 is running.
Task 460141958 rejected.
Task 312714112 rejected.
Task 692404036 rejected.
Task 1554874502 rejected.
task-3 is running.
task-5 is running.
task-4 is running.
task-6 is running.
task-7 is running.
task-8 is running.
task-9 is running.
task-12 is running.
task-11 is running.
task-10 is running.

Java自帶的線程池ThreadPoolExecutor詳細介紹說明和實例應用 
http://fulong258.blog.163.com/blog/static/17895044201082951820935

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章