Java,如何阻止线程 [英] Java, how to stop threads

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

问题描述

所以我创建了一个线程

Thread personThread = new Thread(Person);
personThread.start();

/** Now to stop it **/
personThread.stop();

问题是,当我尝试编译时,我得到:警告:[弃用] Thread中的stop()已被弃用。据我所知,这已经不再使用了。那我怎么能完全停止一个线程,与它的状态无关呢?

The problem is, when I try to compile I get: warning: [deprecation] stop() in Thread has been deprecated. As I am to understand, this is no longer used method. How can I then completely stop a thread, irrelevant of it's status?

推荐答案

你应该中断 a线程,这是一种让它停止的温和方式。

You should interrupt a thread, which is a gentle way of asking it to stop.

我自己的无耻副本

final Thread thread = new Thread(someRunnable);
thread.start();

而不是 stop()致电 interrupt()

thread.interrupt();

并在线程中手动处理中断:

And handle the interruption manually in the thread:

while(!Thread.currentThread().isInterrupted()){
    try{        
        Thread.sleep(10);
    }
    catch(InterruptedException e){
        Thread.currentThread().interrupt();
    }

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

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