Java ExecutorService 暂停/恢复特定线程 [英] Java ExecutorService pause/resume a specific thread

查看:31
本文介绍了Java ExecutorService 暂停/恢复特定线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 ExecutorService 来暂停/恢复特定线程?

Is there a way to use ExecutorService to pause/resume a specific thread?

private static ExecutorService threadpool = Executors.newFixedThreadPool(5);

想象一下,我想停止 id=0 的线程(假设为每个线程分配一个增量 id,直到达到线程池的大小).

Imagine that I want to stop the thread which as the id=0 (assuming that to each one is assigned an incremental id until the size of the threadpool is reached).

过了一会儿,假设按下一个按钮,我想恢复该特定线程,并让所有其他线程保持当前状态,可以暂停或恢复.

After a while, by pressing a button let's say, I want to resume that specific thread and leave all the other threads with their current status, which can be paused or resumed.

我在 Java 文档中发现了一个未完成的 PausableThreadPoolExecutor 版本.但它不适合我的需要,因为它会恢复池中的所有线程.

I have found on Java documentation a uncompleted version of PausableThreadPoolExecutor. But it doesn't suit what I need because it resume all the threads in the pool.

如果使用 ExecutorService 的默认实现无法做到这一点,谁能指出我针对此问题的 Java 实现?

If there's no way to do it with the default implementation of the ExecutorService can anyone point me to a Java implementation for this problem?

推荐答案

你走错了路.线程池拥有线程,通过与您的代码共享它们可能会搞砸.
您应该专注于使您的任务(传递给线程可取消/可中断),而不是直接与池拥有的线程交互.
此外,当您尝试中断线程时,您将不知道正在执行什么作业,因此我不明白您为什么有兴趣这样做

You are on the wrong track. The thread pool owns the threads and by sharing them with your code could mess things up.
You should focus on making your tasks (passed to the threads cancellable/interruptable) and not interact with the threads owned by the pool directly.
Additionally you would not know what job is being executed at the time you try to interrupt the thread, so I can't see why you would be interested in doing this

更新:
取消你在线程池中提交的任务的正确方法是通过执行器返回的任务的Future.
1)通过这种方式,您可以确定您实际瞄准的任务已被尝试取消
2)如果您的任务已经设计为可取消,那么您就完成了一半
3) 不要使用标志来表示取消,而是使用 Thread.currentThread().interrupt() 代替

更新:

public class InterruptableTasks {  

    private static class InterruptableTask implements Runnable{  
        Object o = new Object();  
        private volatile boolean suspended = false;  

        public void suspend(){          
            suspended = true;  
        }  

        public void resume(){       
            suspended = false;  
            synchronized (o) {  
                o.notifyAll();  
            }  
        }  


        @Override  
        public void run() {  

            while(!Thread.currentThread().isInterrupted()){  
                if(!suspended){  
                    //Do work here      
                }
                else{  
                    //Has been suspended  
                    try {                   
                        while(suspended){  
                            synchronized(o){  
                                o.wait();  
                            }                           
                        }                       
                    }  
                    catch (InterruptedException e) {                    
                    }             
                }                           
            }  
            System.out.println("Cancelled");        
        }

    }

    /**  
     * @param args  
     * @throws InterruptedException   
     */  
    public static void main(String[] args) throws InterruptedException {  
        ExecutorService threadPool = Executors.newCachedThreadPool();  
        InterruptableTask task = new InterruptableTask();  
        Map<Integer, InterruptableTask> tasks = new HashMap<Integer, InterruptableTask>();  
        tasks.put(1, task);  
        //add the tasks and their ids

        Future<?> f = threadPool.submit(task);  
        TimeUnit.SECONDS.sleep(2);  
        InterruptableTask theTask = tasks.get(1);//get task by id
        theTask.suspend();  
        TimeUnit.SECONDS.sleep(2);  
        theTask.resume();  
        TimeUnit.SECONDS.sleep(4);                
        threadPool.shutdownNow();      
    }

这篇关于Java ExecutorService 暂停/恢复特定线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆