Thread提供了stop()方法终止线程,但是该方法是强行终止,容易产生一些错误,已经被废弃。可以使用退出标志来终止线程,在run()函数里面设置while循环,把退出标志作为while的条件,当条件为false时,run函数执行完毕,线程就自动终止了。package com. ...
Thread提供了stop()方法终止线程,但是该方法是强行终止,容易产生一些错误,已经被废弃。
可以使用退出标志来终止线程,在run()函数里面设置while循环,把退出标志作为while的条件,当条件为false时,run函数执行完毕,线程就自动终止了。
package com.my_code.thread;public class MyThread extends Thread { public volatile boolean isRunning = true; public void run(){ while (isRunning){ try { sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void stopIt(){ isRunning = false; } public static void main(String[] args) throws InterruptedException{ MyThread thread = new MyThread(); thread.start(); sleep(10000); thread.stopIt(); thread.join(); System.out.println("线程已经退出!"); } }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:Java终止线程
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。