线程终止 java_Java 中不同情况下的线程终止

class FirstThread extends Thread

{

//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程

public volatile boolean exit = false;

int count = 0;

public void run()

{

System.out.println(getName()+"is starting");

//执行run()方法前监测变量exit的值,若为true 则退出线程

while(!exit)

{

System.out.println(getName()+"is runing"+count++);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

System.out.println(getName()+"即将从阻塞中退出");

System.out.println("this.isInterrupted()"+this.isInterrupted());

}

//使用条件退出线程

if(count == 10)

{

exit = true;

}

}

}

}

public class llp_java

{

public static void main(String[] args) throws InterruptedException

{

FirstThread thread1 = new FirstThread();

thread1.start();

//或在主函数中直接结束线程

thread1.exit = true;

System.out.println("线程退出");

}

}

结束非运行状态的线程:

如果线程调用了可中断等待方法,正处于等待状态,此时并是执行run()方法中的while循环,无法根据前面的全局变量的判定退出线程。此时可以通过调用Thread的interrupt方法让等待方法抛出InterruptedException异常,然后在循环外截获并处理异常,这样便跳出了线程run方法中的循环,以使线程顺利结束。使用方法如下:

class FirstThread extends Thread

{

//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程

public volatile boolean exit = false;

int count = 0;

public void interrupt()

{

//复写中断函数,改变exit的状态

exit = true;

}

public void run()

{

System.out.println(getName()+"is starting");

while(!exit)

{

System.out.println(getName()+"is runing"+count++);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

//捕获阻塞中断后调用interrupted()函数,结束线程

Thread.interrupted();

System.out.println(getName()+"即将从阻塞中退出");

System.out.println("this.isInterrupted()"+this.isInterrupted());

}

//if(count == 10)

//{

// exit = true;

//}

}

}

}

public class llp_java

{

public static void main(String[] args) throws InterruptedException

{

FirstThread thread1 = new FirstThread();

thread1.start();

//直接调用中断函数,或者有阻塞中断发生时,会自动调用该函数

thread1.interrupt();

// thread1.join();

System.out.println("线程退出");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值