• SimpleThreadPool给线程池增加拒绝策略和停止方法


    给线程池增加拒绝策略和停止方法

    package com.dwz.concurrency.chapter13;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    
    public class SimpleThreadPool3 {
        private final int size;
        private final int queueSize;
        private final static int DEFAULT_SIZE = 10;
        private final static int DEFAULT_TASK_QUEUE_SIZE = 2000;
        private static volatile int seq = 0;
        private final static String THREAD_PREFIX = "SIMPLE_THREAD_POOL-";
        private final static ThreadGroup GROUP = new ThreadGroup("Pool_Group");
        private final static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>();
        private final static List<WorkerTask> THREAD_QUEUE = new ArrayList<>();
        private final DiscardPolicy discardPolicy;
        private final static DiscardPolicy DEFAULT_DISCARD_POLICY = ()->{
            throw new DiscardException("Discard this task.");
        };
        private volatile boolean destroy = false;
    
        public SimpleThreadPool3() {
            this(DEFAULT_SIZE, DEFAULT_TASK_QUEUE_SIZE, DEFAULT_DISCARD_POLICY);
        }
    
        public SimpleThreadPool3(int size, int queueSize, DiscardPolicy discardPolicy) {
            this.size = size;
            this.queueSize = queueSize;
            this.discardPolicy = discardPolicy;
            init();
        }
    
        private void init() {
            for (int i = 0; i < this.size; i++) {
                createWorkTask();
            }
        }
    
        public void submit(Runnable runnable) {
            if(destroy) {
                throw new IllegalStateException("The thread pool already destroy and not allow submit task.");
            }
            synchronized (TASK_QUEUE) {
                if(TASK_QUEUE.size() >= this.queueSize) {
                    discardPolicy.discard();
                }
                TASK_QUEUE.addLast(runnable);
                TASK_QUEUE.notifyAll();
            }
        }
    
        private void createWorkTask() {
            WorkerTask task = new WorkerTask(GROUP, THREAD_PREFIX + (seq++));
            task.start();
            THREAD_QUEUE.add(task);
        }
        
        public void shutdown() throws InterruptedException {
            while (!TASK_QUEUE.isEmpty()) {
                Thread.sleep(50);
            }
            int initVal = THREAD_QUEUE.size();
            while (initVal > 0) {
                for(WorkerTask task : THREAD_QUEUE) {
                    if(task.getTaskState() == TaskState.BLOCKED) {
                        task.interrupt();
                        task.close();
                        initVal--;
                    } else {
                        Thread.sleep(10);
                    }
                }
            }
            this.destroy = true;
            System.out.println("The thread pool disposed.");
        }
        
        public int getSize() {
            return size;
        }
    
        public int getQueueSize() {
            return queueSize;
        }
        
        public boolean destroy() {
            return destroy;
        }
        
        private enum TaskState {
            FREE, RUNNING, BLOCKED, DEAD
        }
        
        public static class DiscardException extends RuntimeException {
    
            public DiscardException(String message) {
                super(message);
            }
        }
        
        public interface DiscardPolicy{
            void discard() throws DiscardException;
        }
        
        private static class WorkerTask extends Thread {
            private volatile TaskState taskState = TaskState.FREE;
    
            public WorkerTask(ThreadGroup group, String name) {
                super(group, name);
            }
    
            public TaskState getTaskState() {
                return this.taskState;
            }
    
            @Override
            public void run() {
                OUTER: 
                while (this.taskState != TaskState.DEAD) {
                    Runnable runnable = null;
                    synchronized (TASK_QUEUE) {
                        while (TASK_QUEUE.isEmpty()) {
                            try {
                                this.taskState = TaskState.BLOCKED;
                                TASK_QUEUE.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                // 线程被打断回到OUTER位置
                                break OUTER;
                            }
                        }
                        runnable = TASK_QUEUE.removeFirst();
                    }
                    
                    if (runnable != null) {
                        System.out.println("runnable into...");
                        this.taskState = TaskState.RUNNING;
                        runnable.run();
                        this.taskState = TaskState.FREE;
                    }
                }
            }
    
            public void close() {
                this.taskState = TaskState.DEAD;
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            SimpleThreadPool3 threadPool = new SimpleThreadPool3();
    //        IntStream.range(0, 40).forEach(i -> {
    //            threadPool.submit(() -> {
    //                System.out.println("The runnable " + i + " be serviced by " + Thread.currentThread() + " start.");
    //                try {
    //                    Thread.sleep(1000);
    //                } catch (InterruptedException e) {
    //                    e.printStackTrace();
    //                }
    //                System.out.println("The runnable " + i + " be serviced by " + Thread.currentThread() + " finished.");
    //            });
    //        });
            for(int i = 0; i < 40; i++) {
                threadPool.submit(() -> {
                    System.out.println("The runnable be serviced by " + Thread.currentThread() + " start.");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("The runnable be serviced by " + Thread.currentThread() + " finished.");
                });
            }
            
            Thread.sleep(10_000);
            threadPool.shutdown();
            threadPool.submit(()->{System.out.println("=======================");});
        }
    }
  • 相关阅读:
    使用jQuery和CSS自定义HTML5 Video 控件 简单适用
    在win7系统下使用Windows XP Mode 和 Windows Virtual PC搭建window xp系统
    Runtime 解读
    Reachability实时监控网络变化
    关于AsyncSocket
    关于CoreData的用法
    邓白氏编码申请
    Android 到底是个什么东西?
    听 Fabien Potencier 谈Symfony2 之 《What is Symfony2 ?》
    听 Fabien Potencier 谈Symfony2 之 《What is Dependency Injection ?》
  • 原文地址:https://www.cnblogs.com/zheaven/p/12090464.html
Copyright © 2020-2023  润新知