简体   繁体   中英

Stopping or Interrupting a Java Thread

I am trying to stop a java thread if it is running for 6000 milliseconds.

Below code to kill the Thread R1 is failed to stop the thread. could you please correct code?

I have tried this code with while (!Thread.currentThread().isInterrupted()) to stop the thread.

import java.time.Duration;
import java.time.Instant;

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;

    ThreadDemo(String name) {
        threadName = name;
        System.out.println("Creating " + threadName);
    }

    @Override
    public void run() {
        System.out.println("Running " + threadName);
        try {
            while (!Thread.currentThread().isInterrupted()) {
                for (int i = 100; i > 0; i--) {
                    System.out.println("Thread: " + threadName + ", " + i);
                    // Let the thread sleep for a while.
                    Thread.sleep(600);
                }
            }
        } catch (InterruptedException e) {
            System.out.println("Thread " + threadName + " interrupted.");
            Thread.currentThread().interrupt();

        }
        System.out.println("Thread " + threadName + " exiting.");
    }

    @Override
    public void start() {
        System.out.println("Starting " + threadName);
        if (t == null) {
            t = new Thread(this, threadName);
            t.start();
        }
    }
}

public class Killthread {

    public static void main(String args[]) throws InterruptedException {
        Instant timeBefore = Instant.now();

        ThreadDemo R1 = new ThreadDemo("Thread-1");
        R1.start();
        System.out.println("Afte thread start");
        Thread.sleep(6001);
        Instant timeAfter = Instant.now();
        if (Duration.between(timeBefore, timeAfter).toMillis() > 6000) {
            R1.interrupt();
            // R1.stop();
            System.out.println("Thread Interrupted due to Time limitation.");

        }
    }
}

You've got two problems in your code, firstly that you aren't sleeping your main thread long enough, and secondly that you're interrupting the wrong thread.

6001 ms isn't long enough to guarantee that your duration check will be true. When I run your code, the main method rarely enters the if block. If you change to it sleep for 6100 ms, it should consistently call the interrupt.

Your second problem is that you're interrupting R1 , but you need to be interrupting t .

If you override interrupt() in ThreadDemo to pass the call down to t , then it will receive the interrupt and break its execution thread.

eg

@Override public void interrupt() {
    t.interrupt();
}

The problem is, that you start a complete new, different and unnecessary thread in ThreadDemo::start .

@Override
public void start() {
    System.out.println("Starting " + threadName);
    if (t == null) {
        t = new Thread(this, threadName);
        t.start();
    }
}

It should rather look like

@Override
public void start() {
    System.out.println("Starting " + threadName);
    super.start();
}

And get rid of that private Thread t; in ThreadDemo .

为了从您覆盖的启动方法中调用t.start(),请调用super.start(),它将调用线程类的start(),并负责创建新线程并将其注册到线程调度程序中。

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