I am creating multiple threads from a timertask, and everything is working fine for first execution of timertask. But when timertask is executed for second time,Thread.start() is not invoking run() method. I have tried every option I came across on internet,but nothing works. Can anyone please help me !!! :(
This is how I schedule timertask:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new orderProcessScheduler(), getDate(), interval_period);
Here's the 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();
}
}
Here's thread implementation:
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();
}
new Thread(this).start()in a constructor! It potentially allows the new thread to see thethisobject in a partially initialized or uninitialized state. Google for "leaking this" for more information.threadPoolhas a deceptive name: Deceptive because it's not a pool if you don't re-use the threads. Your timer task creates all new threads each time it is run.