0

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);
halfer
  • 19,824
  • 17
  • 99
  • 186
Trts
  • 985
  • 1
  • 11
  • 24
  • 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,226
  • 2
  • 22
  • 35
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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Braj
  • 46,415
  • 5
  • 60
  • 76