永发信息网

java如何关闭线程

答案:1  悬赏:40  手机版
解决时间 2021-01-10 10:28
  • 提问者网友:伴风望海
  • 2021-01-09 21:19
java如何关闭线程
最佳答案
  • 五星知识达人网友:詩光轨車
  • 2021-01-09 21:29
关闭线程有几种方法,
一种是调用它里面的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();
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯