停止或中断Java线程

时间:2016-09-26 15:52:18

标签: java multithreading

如果java线程运行6000毫秒,我试图阻止它。

下面杀死线程R1的代码无法停止线程。你可以请更正代码吗?

我尝试使用while(!Thread.currentThread()。isInterrupted())来停止线程。

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

        }
    }
}

3 个答案:

答案 0 :(得分:3)

你的代码中有两个问题,首先是你没有足够长时间地睡觉你的主线程,其次是你正在打断错误的线程。

6001 ms不足以保证您的持续时间检查是真的。当我运行你的代码时,main方法很少进入if块。如果你改为睡眠6100 ms,它应该一直调用中断。

您的第二个问题是您正在中断R1,但您需要打断t

如果在ThreadDemo中覆盖interrupt()以将调用传递给t,那么它将接收中断并中断其执行线程。

e.g。

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

答案 1 :(得分:1)

问题是,你在ThreadDemo::start开始一个全新的,不同的和不必要的线程。

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

它应该看起来像

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

并删除private Thread t;中的ThreadDemo

答案 2 :(得分:1)

请从重写的start方法调用t.start()调用super.start(),它将调用线程类的start(),并负责创建新线程并使用线程调度程序注册它。