Java:如何停止线程? [英] Java: How to stop thread?

查看:120
本文介绍了Java:如何停止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从线程的OUTSIDE停止另一个线程?
比如,如果我运行一个线程来运行该线程并导致该线程停止?它会阻止其他线程吗?

Is there any way to stop another thread from OUTSIDE of the thread? Like, if I ran a thread to run that thread and caused that thread to stop? Would it stop the other thread?

有没有办法在没有循环的情况下从内部停止线程?
例如,如果您正在理想地下载,则需要使用循环,如果我使用循环,我将无法暂停它直到它到达循环结束。

Is there a way to stop the thread from inside without a loop? For example, If you are downloading ideally you would want to use a loop, and if I use a loop I wont be able to pause it until it reaches the end of the loop.

推荐答案

我们不会停止或杀死一个线程,而是我们做 Thread.currentThread()。isInterrupted()。

We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().

public class Task1 implements Runnable {
    public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                       ................
                       ................
                       ................
                       ................
           }
    }
}

主要我们会这样做:

Thread t1 = new Thread(new Task1());
t1.start();
t1.interrupt();

这篇关于Java:如何停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆