2016-03-01 77 views
1

我从timertask创建多个线程,并且对于第一次执行timertask,一切工作正常。但是当第二次执行timertask时,Thread.start()不会调用run()方法。我尝试了所有在互联网上遇到的选项,但没有任何效果。谁能帮帮我吗 !!! :(TimerTask + multiThreading + java,不适用于第二次执行

我这是怎么安排的TimerTask:

Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new orderProcessScheduler(), getDate(), interval_period); 

这里是一个TimerTask:

public class orderProcessScheduler extends TimerTask{ 

public void processOrders() 
{ 
    try 
    { 

     int totalThreads = 10; 
     List<orderThreadImpl> threadPool = new ArrayList<orderThreadImpl>(); 

     for(int i = 0;i<totalThreads;i++) 
     { 
      threadPool.add(new orderThreadImpl()); 
     } 

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

@Override 
public void run() { 
    // TODO Auto-generated method stub 
    processOrders(); 
} 
} 

这里的线程中执行:

public class orderThreadImpl implements Runnable{ 

private Thread t; 


@Override 
public void run() { 
    // TODO Auto-generated method stub 

    try 
    { 

     // code for what this thread is suppose to do 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

public orderThreadImpl() 
{ 
    this.t = new Thread(this); 
    t.start(); 
} 
+1

你应该考虑使用的ThreadPoolExecutor https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html – Xvolks

+1

不要做'新主题(这一点)。 start()'在构造函数中!它可能允许新线程以部分初始化或未初始化的状态查看“this”对象。谷歌“泄漏这个”了解更多信息。 –

+0

你的变量'threadPool'有一个欺骗性的名字:欺骗性的,因为如果你不重新使用线程它不是_pool_。您的计时器任务会在每次运行时创建所有新线程。 –

回答

0

这里是你应该做的,用执行者服务线程池来管理你的线程,并为你启动每个线程:

import java.util.Timer; 
import java.util.TimerTask; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.ThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 

public class TimerTaskQuestion { 

    public static void main(String[] args) { 
     OrderProcessScheduler orderScheduler = new OrderProcessScheduler(); 
     Timer timer = new Timer(); 
     timer.schedule(orderScheduler, 500, 1000); 
    } 

    public static class OrderProcessScheduler extends TimerTask { 

     private ExecutorService ex; 

     public OrderProcessScheduler() { 
      this.ex = Executors.newFixedThreadPool(10); 
      try { 
       this.ex.awaitTermination(1, TimeUnit.SECONDS); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
     @Override 
     public void run() { 
      System.out.println("Number of active thread : " + ((ThreadPoolExecutor)this.ex).getActiveCount()); 
      this.ex.execute(new orderThreadImpl()); 
     } 

     public void initiateShutdown(){ 
      this.ex.shutdown(); 
     } 
    } 

    public static class orderThreadImpl implements Runnable { 

     @Override 
     public void run() { 
      try { 
       System.out.println("Executed from : " + Thread.currentThread().getName()); 
       Thread.sleep(3000); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
相关问题