java多线程--线程中断


        当一个线程在运行的时候在另一个线程中可以通过Thread对象的interrupt()方法来中断它。如果仅仅调用了interrupt()线程还是会继续执行的,因为Thread.interrupt() 对正在运行的线程是不起作用的,只有对阻塞的线程有效。如果要中断后离开线程,可以有以下几种方法:

1. 用Thread对象interrupt()方法来中断阻塞的线程如sleep中的线程。

对于阻塞的线程,调用interrupt()后会抛出InterruptedException异常,可以通过捕获该异常来退出。如:

public class InterruptTest implements Runnable {
public void run() {
try {
System.out.println("in run() sleep 20 seconds");
Thread.sleep(20000);
System.out.println("in run() wakeup");
} catch (InterruptedException e) {
System.out.println("in run() sleep interrupted while sleeping");
//如果没有return,那么即使中断,程序也会继续往下执行
return;
}


System.out.println("in run leaving normaly");


}


public static void main(String[] args) {
InterruptTest it = new InterruptTest();
Thread t = new Thread(it);
t.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("in main interrupe other thread");
t.interrupt();
System.out.println("in main leaving");


}


}


运行结果:

in run() sleep 20 seconds
in main interrupe other thread
in main leaving
in run() sleep interrupted while sleeping

2. 通过Thread.interrupted()中断线程

Thread.interrupted()可以判断中断的状态,isInterrupted()方法也可以检查线程的状态,区别是前者由于是静态方法,只能检查调用它的线程的中断状态。线程一旦被中断,那么Thread.interrupted()会返回true并把转太变为false。而isInterrupted()却不会自动重置中断状态,当线程被中断,isInterrupted()返回ture,一旦sleep抛出异常,中断状态会被清空,这时候isInterrupted()会返回false。

public class InterruptedCheck1 implements Runnable{
public void run(){
while
(!Thread.interrupted()){

System.out.println("was not interrupted");
}
}

public static void main(String[] args) {
InterruptedCheck1 ic = new InterruptedCheck1();
Thread t = new Thread(ic);
t.start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("interrupted other thread");
t.interrupt();


}


3.通过一个公共变量来中断线程。

public class InterruptedCheck2 implements Runnable{
volatile boolean stop = false;
public void run(){
while(!stop){
System.out.println("I an running...");
}
System.out.println("was interrupted");
}

public static void main(String[] args) throws InterruptedException {
InterruptedCheck2 ic = new InterruptedCheck2();
Thread t = new Thread(ic);
t.start();
Thread.sleep(200);
System.out.println("interrupted other thread");
ic.stop = true;
Thread.sleep(200);
System.out.println("main exit");
}
}


4.yield和join两个方法的使用。

 join: 只能用线程对象调用,如果在线程B中调用线程A的join方法,那么线程B会等待线程A执行完后再执行。

yield:可以用线程对象调用也可以用Thread对类调用,yield让出cpu的执行权给同等级线程,如果没有同等级的线程在等待          cpu,则该线程继续执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值