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);
1
  • 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). Commented Mar 18, 2014 at 5:36

2 Answers 2

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

Comments

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.

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.