public class Test{
  public static void main(String[] args) {
    ScheduledThreadPoolExecutor exe = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
for(int i=1;i<8;i++){
  p.addThread(new TestThread(i));
}
  }
}
public class TestThread extends Thread{
    int i ;
    public TestThread(int i) {
        this.i = i;
    }    public void run(){
        System.out.println("TestThread run:" + i);
        if(i==3){
            /////  添加新线程                      
        }
        try {
            sleep(5000);
        } catch (InterruptedException ex) {
        }
       
    }
}我想做执行到第3个线程时,向ScheduledThreadPoolExecutor插入一个线程,然后再执行完第3个线程后立即执行新插入的线程,执行完新插入的线程后,再继续执行原来的第4个线程请问ScheduledThreadPoolExecutor能做到吗?

解决方案 »

  1.   

    ScheduledThreadPoolExecutor做不到,能提供实现上述功能的替换方案吗?
    谢谢
      

  2.   

    上面的代码有点错误,请看下面的代码:
    public class Test{ 
      public static void main(String[] args) { 
        ScheduledThreadPoolExecutor exe = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); 
    for(int i=1;i <8;i++){ 
      exe.schedule(new TestThread(i,exe), 5, TimeUnit.SECONDS); 
      } 

    public class TestThread extends Thread{ 
        int i ; 
    ScheduledThreadPoolExecutor exe;
        public TestThread(int i,ScheduledThreadPoolExecutor exe) { 
            this.i = i; 
            this.exe = exe;
        }     public void run(){ 
            System.out.println("TestThread run:" + i); 
            if(i==3){ 
                /////  添加新线程 
                exe.schedule(new TestThread(10,exe), 5, TimeUnit.SECONDS); 
                 
            } 
            try { 
                sleep(5000); 
            } catch (InterruptedException ex) { 
            } 
          
        } 

    我想做执行到第3个线程时,向ScheduledThreadPoolExecutor插入一个线程,然后再执行完第3个线程后立即执行新插入的线程,执行完新插入的线程后,再继续执行原来的第4个线程 请问ScheduledThreadPoolExecutor能做到吗?