简体   繁体   中英

Difficulty with timer and threading in Java

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);

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM