1

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();
}
6
  • 1
    You should consider using a ThreadPoolExecutor docs.oracle.com/javase/7/docs/api/java/util/concurrent/… Commented Mar 1, 2016 at 14:25
  • 1
    Don't do new Thread(this).start() in a constructor! It potentially allows the new thread to see the this object in a partially initialized or uninitialized state. Google for "leaking this" for more information. Commented Mar 1, 2016 at 14:43
  • Your variable threadPool has 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. Commented Mar 1, 2016 at 14:47
  • Re, when timertask is executed for second time,Thread.start() is not invoking run(). How do you know? What behavior are you expecting? What do you get instead? Consider creating an SSCCE and posting it here. sscce.org Commented Mar 1, 2016 at 14:48
  • Thanks @Xvolks for your help Benoit's answer below also suggested same API, and that worked :) Commented Mar 2, 2016 at 9:49

1 Answer 1

1

Here is what you should do, use an executor service thread pool to manage your threads, and start each thread for you :

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();
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.