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();
}
你應該考慮使用的ThreadPoolExecutor https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html – Xvolks
不要做'新主題(這一點)。 start()'在構造函數中!它可能允許新線程以部分初始化或未初始化的狀態查看「this」對象。谷歌「泄漏這個」瞭解更多信息。 –
你的變量'threadPool'有一個欺騙性的名字:欺騙性的,因爲如果你不重新使用線程它不是_pool_。您的計時器任務會在每次運行時創建所有新線程。 –