Java,如何阻止线程

ved*_*ran 4 java multithreading

所以我创建了一个线程

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

/** Now to stop it **/
personThread.stop();
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*icz 6

你应该打断一个线程,这是一种让它停止的温和方式.

我的无耻副本:

final Thread thread = new Thread(someRunnable);
thread.start();
Run Code Online (Sandbox Code Playgroud)

而不是stop()电话interrupt():

thread.interrupt();
Run Code Online (Sandbox Code Playgroud)

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

while(!Thread.currentThread().isInterrupted()){
    try{        
        Thread.sleep(10);
    }
    catch(InterruptedException e){
        Thread.currentThread().interrupt();
    }
Run Code Online (Sandbox Code Playgroud)