其他分享
首页 > 其他分享> > ThreadPoolExecutor 线程执行超时

ThreadPoolExecutor 线程执行超时

作者:互联网

 

package com.vipsoft.Thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorTest {

    public static void main(String[] args) throws Exception {
        int corePoolSize = 2;
        int maximumPoolSize = 5;
        long keepAliveTime = 10;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(3);  //定义一个大小为2的队列,只等有一个任务在排队等,多出来的需要开新线程
        ThreadFactory threadFactory = new MyTreadFactory();
        RejectedExecutionHandler handler = new MyPolicy();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        System.out.println("预启动线程(备战)");
        executor.prestartAllCoreThreads(); // 预启动所有核心线程,处于备战
        System.out.println("预启动线程数(备战):" + executor.getPoolSize());
        for (int i = 1; i <= 10; i++) {
            System.out.println(System.currentTimeMillis() + "  " + "开始 下发任务:" + i + " 当前线程总数:" + executor.getPoolSize());
            MyTask task = new MyTask(String.valueOf(i));
            executor.execute(task);
            System.out.println(System.currentTimeMillis() + "  " + "完成 下发任务:" + i + " 当前线程总数:" + executor.getPoolSize() + " 队列中的线程数量:" + workQueue.size());
            Thread.sleep(1); //停1毫秒,日志记录,时间后方便分析
            if (i == 9) {
                //TODO Thread.sleep(3000); //任务9下发后【会被拒绝】,停3秒,等队列或线程释放后,再下发任务10,这时候任务10不会被拒绝
            }
        }
        System.in.read(); //阻塞主线程
    }

    static class MyTreadFactory implements ThreadFactory {

        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "Thread-" + mThreadNum.getAndIncrement());
            System.out.println(System.currentTimeMillis() + "  " + t.getName() + " has been created");
            return t;
        }
    }

    public static class MyPolicy implements RejectedExecutionHandler {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            // 可做日志记录等
            System.err.println(System.currentTimeMillis() + "  " + r.toString() + " rejected from " + e.toString());
        }
    }

    static class MyTask implements Runnable {
        private String name;

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

        @Override
        public void run() {
            try {
                Thread mainT = Thread.currentThread();
                String threadName = this.name;
                SubThread st = new SubThread(threadName, mainT);
                Thread thread = new Thread(st);
                thread.start();
                try {
                    System.out.println(System.currentTimeMillis() + "  " + this.toString() + " 开始运行! " + Thread.currentThread().getName());
                    Thread.sleep(Integer.valueOf(threadName) * 1000); //让任务执行慢点
                    st.setDone();
                    System.out.println(System.currentTimeMillis() + "  " + this.toString() + " 运行结束! " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    System.out.println("主线程,被打断 " + threadName);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "MyTask [name=" + this.name + "]";
        }

        static class SubThread implements Runnable {
            private String name;
            private Thread mainT;

            //如果完成了就不用杀了。
            private boolean isDone;

            public void setDone() {
                isDone = true;
            }

            public SubThread(String name, Thread mainT) {
                this.name = name;
                this.mainT = mainT;
            }

            @Override
            public void run() {
                try {
                    System.out.println("子线程,正在监控主进程 " + name);
                    Thread.sleep(5000);
                    //时间到了,主线程还没有完成就干掉。
                    if (!isDone) {
                        mainT.interrupt();
                        System.out.println("子线程,干掉了主进程(超时了) " + name);
                    }
                } catch (InterruptedException e) {
                    System.out.println("子线程,被打断");
                    return;
                }
            }

            @Override
            public String toString() {
                return "MyTask [name=" + this.name + "]";
            }
        }
    }


}

 

标签:int,备战,线程,executor,new,超时,ThreadPoolExecutor
来源: https://www.cnblogs.com/vipsoft/p/16363231.html