2016-03-01 76 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(); 
      } 
     } 
    } 
} 
相關問題