Search code examples
javamultithreadingtimer

Difficulty with timer and threading in Java


Two threads start. I want to interrupt the first thread in 2 seconds. What have I done wrongly with my timer? It seems to be not interrupting the thread.

class ThreadTask extends TimerTask {

    @Override
    public void run() {
        firstThread.interrupt();
        System.out.println("firstThread has been terminated.");
    } // run
} // class ThreadTask

Timer timer = new Timer();
ThreadTask task = new ThreadTask();
timer.schedule(task, new Date().getTime() + 3000);

Solution

  • A sample code to interrupt a thread.

    Check for Thread.currentThread().isInterrupted() in Thread.run() method.

    Timer must be started from Thread.run() method if you want to interrupt it after 3 seconds from starting its execution.

        import java.util.Timer;
    import java.util.TimerTask;
    
    public class ThreadTimer implements Runnable {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            new Thread(new ThreadTimer()).start();
        }
    
        @Override
        public void run() {
            Timer timer = new Timer();
            ThreadTask task = new ThreadTask(Thread.currentThread());
            timer.schedule(task, 3000);
    
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    break;
                }
                System.out.println(Math.random() * 1000);
                // do whatever you want to do here
            }
        }
    
    }
    
    class ThreadTask extends TimerTask {
    
        private Thread thread;
    
        public ThreadTask(Thread thread) {
            this.thread = thread;
        }
    
        @Override
        public void run() {
            thread.interrupt();
            System.out.println("Thread has been terminated.");
        } // run
    } // class ThreadTask
    

    If above code doesn't fit as per you requirement then use ExecutorService.awaitTermination() as a best option to do this.

    Here is a sample code.