0

Two threads start. I want to interrupt the first thread in 2 seconds. Could you help me understand 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);
Mohammad Ashfaq
  • 1,313
  • 2
  • 14
  • 37
Trts
  • 939
  • 1
  • 11
  • 22
  • 1
    Where is "firstThread" defined? Perhaps you are simply not handling interruption properly. (Note that interruption is cooperative, so your other thread needs to check for interruption to exit). – Michael Aaron Safyan Mar 18 '14 at 05:36

2 Answers2

2

It seems that there is an error in the use of the method Timer.schedule.

You are using:

public void schedule(TimerTask task, long delay) Schedules the specified task for execution after the specified delay. Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed.

If you take the current time + 2 seconds, then the thread will stop working through ~44 years.

Use:

timer.schedule(task, 3000);
DmitryKanunnikoff
  • 2,176
  • 1
  • 20
  • 33
0

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

Community
  • 1
  • 1
Braj
  • 45,615
  • 5
  • 55
  • 73