永发信息网

java中怎样管理线程,当我线程执行完后,能自动关闭,也可以外部调用关闭所有正在运行的线程...

答案:2  悬赏:0  手机版
解决时间 2021-02-14 03:25
  • 提问者网友:贪了杯
  • 2021-02-13 22:15
java中怎样管理线程,当我线程执行完后,能自动关闭,也可以外部调用关闭所有正在运行的线程...
最佳答案
  • 五星知识达人网友:狂恋
  • 2021-02-13 23:38
在手动关闭没有用到的线程,就像你文件打开后要关闭一样。不关闭文件数据就读不到了一样。
全部回答
  • 1楼网友:从此江山别
  • 2021-02-14 00:46
关闭线程有几种方法, 一种是调用它里面的stop()方法 另一种就是你自己设置一个停止线程的标记 (推荐这种) 代码如下: package com.demo; //测试thread的stop方法和自己编写一个停止标记来停止线程; public class stopthread implements runnable{ //停止线程的标记值boolean; private boolean flag = true; public void stopthread(){ flag = false; } public void run(){ int i=0; while(flag){ i++; system.out.println(thread.currentthread().getname()+":"+i); try{ thread.sleep(1000); }catch(exception e){ } system.out.println(thread.currentthread().getname()+"==>"+i); } } public static void main(string args[]){ stopthread st = new stopthread(); thread th = new thread(st); thread th1 = new thread(st); th.start(); th1.start(); try{ thread.sleep(5500); }catch(exception e){ } th.stop(); st.stopthread(); } }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯