您的位置:澳门新葡8455最新网站 > 服务器运维 > 澳门新葡8455最新网站java使用暗中同意线程池踩过

澳门新葡8455最新网站java使用暗中同意线程池踩过

发布时间:2019-11-14 16:55编辑:服务器运维浏览(172)

    java使用默许线程池踩过的坑(1)

    场景

    三个调治器,四个调节任务,分别管理四个目录下的txt文件,有些调节任务应对某个复杂难点的时候会随处极度长的光阴,以至有直接不通的大概。大家供给三个manager来治本这个task,当以此task的上三遍实行时间相差未来抢先5个调整周期的时候,就径直停掉那些线程,然后再重启它,保障多少个目的目录下未有待管理的txt文件聚成堆。

    问题

    直白接收java暗中同意的线程池调整task1和task2.出于外界txt的种种不可控原因,引致task2线程拥塞。现象就是task1和线程池调治器都健康运作着,不过task2迟迟未有动作。

    自然,找到切实可行的隔绝原因并张开针对性消除是很关键的。可是,这种方法很只怕并不可能完全、深透、周全的处理好全体未知情形。我们须要确认保证职分线程或许调解器的强健性!

    方案布置

    线程池调节器并从未原生的指向被调治线程的作业运营情况实行监察和控制管理的API。因为task2是堵塞在咱们的事情逻辑里的,所以最棒的法子是写一个TaskManager,全体的天职线程在执行义务前整整到那几个TaskManager这里来注册自身。那个TaskManager就担任对于每种自身管辖范围内的task实行实时全程监督!

    末尾的基本点便是怎样管理抢先5个施行周期的task了。

    方案如下:

    ●大器晚成旦发觉这些task线程,立刻暂停它,然后重新重启;

    ●风度翩翩旦发觉这些task线程,直接将总体pool清空并终止,重新放入那三个task ——task明确的景况下】;

    方案实行

    暂停后重启

    ●Task实现类

    class FileTask extends Thread { private long lastExecTime = 0; protected long interval = 10000; public long getLastExecTime() {     return lastExecTime; } public void setLastExecTime(long lastExecTime) {     this.lastExecTime = lastExecTime; } public long getInterval() {     return interval; } public void setInterval(long interval) {     this.interval = interval; }  public File[] getFiles() {     return null; } 
    

    ●Override

    public void run() { while (!Thread.currentThread().isInterrupted()) { lastExecTime = System.currentTimeMillis(); System.out.println(Thread.currentThread().getName() + " is running -> " + new Date()); try { Thread.sleep(getInterval() * 6 * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace();    // 当线程池shutdown之后,这里就会抛出exception了             }         }     }     } 
    

    ●TaskManager

    public class TaskManager  implements Runnable { private final static Log logger = LogFactory.getLog(TaskManager .class); public Set<FileTask> runners = new CopyOnWriteArraySet<FileTask>(); ExecutorService pool = Executors.newCachedThreadPool(); public void registerCodeRunnable(FileTask process) { runners.add(process); } public TaskManager (Set<FileTask> runners) { this.runners = runners; } 
    

    @Override

    public void run() {        while (!Thread.currentThread().isInterrupted()) {            try {                long current = System.currentTimeMillis();                for (FileTask wrapper : runners) {                    if (current - wrapper.getLastExecTime() > wrapper.getInterval() * 5) {                        wrapper.interrupt();                        for (File file : wrapper.getFiles()) {                            file.delete();                        }                     wrapper.start();                      }                }            } catch (Exception e1) {                logger.error("Error happens when we trying to interrupt and restart a task ");                ExceptionCollector.registerException(e1);            }            try {                Thread.sleep(500);            } catch (InterruptedException e) {            }        }    }     
    

    这段代码会报错 java.lang.Thread IllegalThreadStateException。为啥吧?其实那是四个很底子的标题,您应该不会像自个儿同样马虎。查看Thread.start()的注释, 有那样大器晚成段:

    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

    对的,一个线程不能运营五次。那么它是怎么判定的吧?

    public synchronized void start() {         /**          * A zero status value corresponds to state "NEW".    0对应的是state NEW          */ 
    

    if (threadStatus != 0) //假若不是NEW state,就径直抛出极其!


    澳门新葡8455最新网站 1


    ) 场景 三个调解器,多少个调解职务,分别管理多个目录下的txt文件,某些调整职务应对有个别复杂难题的时候会...

    java中通用的线程池实例代码,java线程池实例

    复制代码 代码如下:
    package com.smart.frame.task.autoTask;

    import java.util.Collection;
    import java.util.Vector;

    /**
     * 职分分发器
     */
    public class TaskManage extends Thread
    {
        protected Vector<Runnable> tasks = new Vector<Runnable>();
        protected boolean running = false;
        protected boolean stopped = false;
        protected boolean paused = false;
        protected boolean killed = false;
        private ThreadPool pool;

        public TaskManage(ThreadPool pool)
        {
            this.pool = pool;
        }

        public void putTask(Runnable task)
        {
            tasks.add(task);
        }

        public void putTasks(Runnable[] tasks)
        {
            for (int i = 0; i < tasks.length; i++)
                this.tasks.add(tasks[i]);
        }

        public void putTasks(Collection<Runnable> tasks)
        {
            this.tasks.addAll(tasks);
        }

        protected Runnable popTask()
        {
            if (tasks.size() > 0) return (Runnable) tasks.remove(0);
            else return null;
        }

        public boolean isRunning()
        {
            return running;
        }

        public void stopTasks()
        {
            stopped = true;
        }

        public void stopTasksSync()
        {
            stopTasks();
            while (isRunning())
            {
                try
                {
                    sleep(5);
                }
                catch (InterruptedException e)
                {
                    TaskException.getResultMessage(e);
                }
            }
        }

        public void pauseTasks()
        {
            paused = true;
        }

        public void pauseTasksSync()
        {
            pauseTasks();
            while (isRunning())
            {
                try
                {
                    sleep(5);
                }
                catch (InterruptedException e)
                {
                    TaskException.getResultMessage(e);
                }
            }
        }

        public void kill()
        {
            if (!running) interrupt();
            else killed = true;
        }

        public void killSync()
        {
            kill();
            while (isAlive())
            {
                try
                {
                    sleep(5);
                }
                catch (InterruptedException e)
                {
                    TaskException.getResultMessage(e);
                }
            }
        }

        public synchronized void startTasks()
        {
            running = true;
            this.notify();
        }

        public synchronized void run()
        {
            try
            {
                while (true)
                {
                    if (!running || tasks.size() == 0)
                    {
                        pool.notifyForIdleThread();
                        this.wait();
                    }
                    else
                    {
                        Runnable task;
                        while ((task = popTask()) != null)
                        {
                            task.run();
                            if (stopped)
                            {
                                stopped = false;
                                if (tasks.size() > 0)
                                {
                                    tasks.clear();
                                    System.out.println(Thread.currentThread().getId() + ": Tasks are stopped");
                                    break;
                                }
                            }
                            if (paused)
                            {
                                paused = false;
                                if (tasks.size() > 0)
                                {
                                    System.out.println(Thread.currentThread().getId() + ": Tasks are paused");
                                    break;
                                }
                            }
                        }
                        running = false;
                    }

                    if (killed)
                    {
                        killed = false;
                        break;
                    }
                }
            }
            catch (InterruptedException e)
            {
                TaskException.getResultMessage(e);
                return;
            }
        }
    }

    复制代码 代码如下:
    package com.smart.frame.task.autoTask;

    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Vector;

    /**
     * 线程池
     */
    public class ThreadPool
    {
        protected int maxPoolSize = TaskConfig.maxPoolSize;
        protected int initPoolSize = TaskConfig.initPoolSize;
        protected Vector<TaskManage> threads = new Vector<TaskManage>();
        protected boolean initialized = false;
        protected boolean hasIdleThread = false;

        public ThreadPool()
        {
            super();
        }

        public ThreadPool(int maxPoolSize, int initPoolSize)
        {
            this.maxPoolSize = maxPoolSize;
            this.initPoolSize = initPoolSize;
        }

        public void init()
        {
            initialized = true;
            for (int i = 0; i < initPoolSize; i++)
            {
                TaskManage thread = new TaskManage(this);
                thread.start();
                threads.add(thread);
            }
        }

        public void setMaxPoolSize(int maxPoolSize)
        {
            this.maxPoolSize = maxPoolSize;
            if (maxPoolSize < getPoolSize()) setPoolSize(maxPoolSize);
        }

        /**
         * 重设当前线程数 若需杀掉某线程,线程不会及时杀掉,而会等到线程中的事
         * 务管理到位 但此方法会即刻从线程池中移除该线程,不会等待事务管理甘休
         */
        public void setPoolSize(int size)
        {
            if (!initialized)
            {
                initPoolSize = size;
                return;
            }
            else if (size > getPoolSize())
            {
                for (int i = getPoolSize(); i < size && i < maxPoolSize; i++)
                {
                    TaskManage thread = new TaskManage(this);
                    thread.start();
                    threads.add(thread);
                }
            }
            else if (size < getPoolSize())
            {
                while (getPoolSize() > size)
                {
                    TaskManage th = (TaskManage) threads.remove(0);
                    th.kill();
                }
            }
        }

        public int getPoolSize()
        {
            return threads.size();
        }

        protected void notifyForIdleThread()
        {
            hasIdleThread = true;
        }

        protected boolean waitForIdleThread()
        {
            hasIdleThread = false;
            while (!hasIdleThread && getPoolSize() >= maxPoolSize)
            {
                try
                {
                    Thread.sleep(5);
                }
                catch (InterruptedException e)
                {
                    TaskException.getResultMessage(e);
                    return false;
                }
            }

            return true;
        }

        public synchronized TaskManage getIdleThread()
        {
            while (true)
            {
                for (Iterator<TaskManage> itr = threads.iterator(); itr.hasNext();)
                {
                    TaskManage th = (TaskManage) itr.next();
                    if (!th.isRunning()) return th;
                }

                if (getPoolSize() < maxPoolSize)
                {
                    TaskManage thread = new TaskManage(this);
                    thread.start();
                    threads.add(thread);
                    return thread;
                }

                if (waitForIdleThread() == false) return null;
            }
        }

        public void processTask(Runnable task)
        {
            TaskManage th = getIdleThread();
            if (th != null)
            {
                th.putTask(task);
                th.startTasks();
            }
        }

        public void processTasksInSingleThread(Runnable[] tasks)
        {
            TaskManage th = getIdleThread();
            if (th != null)
            {
                th.putTasks(tasks);
                th.startTasks();
            }
        }

        public void processTasksInSingleThread(Collection<Runnable> tasks)
        {
            TaskManage th = getIdleThread();
            if (th != null)
            {
                th.putTasks(tasks);
                th.startTasks();
            }
        }

    }

    复制代码 代码如下:
    package com.smart.frame.task.autoTask;

    public class TopTask implements Runnable
    {

        private ThreadPool pool;

        public TopTask()
        {
            super();
        }

        public TopTask(ThreadPool pool)
        {
            super();
            this.pool = pool;
        }

        @Override
        public void run()
        {
            init();
            start();
        }

        /**
         * 开首化验证权限、参数之类
         */
        public void init()
        {

        }

        /**
         * 先河活动职务
         */
        public void start()
        {
            for (int i = 0; i < 10; i++)
            {
                pool.processTask(new BeginAuto());
            }
        }
    }
    /**
     * 实现类
     */
    class BeginAuto implements Runnable
    {
        @Override
        public void run()
        {
            System.out.println(Thread.currentThread().getId() + "..................");
        }

    }

    复制代码 代码如下: package com.smart.frame.task.autoTask; import java.util.Collection; import java.util.Vector;...

    本文由澳门新葡8455最新网站发布于服务器运维,转载请注明出处:澳门新葡8455最新网站java使用暗中同意线程池踩过

    关键词:

上一篇:客商对BSM所陷入的误区,只可远观

下一篇:没有了