如何暂停在ThreadPoolExecutor中运行的特定线程中的工作

时间:2015-05-01 11:55:18

标签: java android threadpoolexecutor

在我的应用中,我通过ThreadsThreadPoolExecutor开始多个媒体下载。现在我希望能够暂停特定的下载线程。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

我不确定你是如何实现你的代码的,所以我只是在这里猜测。

通过跟踪你的主题来实现这一目的的一种方法,

例如创建一个Map:

Map<String,Thread> threads=new HashMap<String,Thread>();// ensure each Thread has a unique id, in this case its supposedly a String. then you can control them from outside your thread pool.

这是一个被黑客攻击的实现:

public class hello{

public static void main(String...strings )throws Exception{

     ExecutorService executor = Executors.newFixedThreadPool(5);
     Map<String,Thread> threads=new HashMap<String, Thread>();
     for(int i=0;i<5;i++){
         Thread t = new myRunnable((i+1) +" ");
         threads.put((i+1)+"", t);
         executor.execute(t);
     }

     Thread.sleep(2000);
    ((myRunnable)threads.get("1")).isSuspened=true;
}

private static class myRunnable extends Thread{
    String a;
    public  boolean isSuspened=false;

    public myRunnable(String a) {
        this.a=a;
        // TODO Auto-generated constructor stub
    }
    @Override
    public void run(){
        while(true){
            if(isSuspened){
                continue;
            }
            try{
                System.out.println(a);
                Thread.sleep(2000);
            }catch(Exception e){}
        }
    }
}
}