您的位置:首页 > 编程语言 > Java开发

java多线程--线程中断

2015-12-07 14:11 721 查看
        当一个线程在运行的时候在另一个线程中可以通过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.
4000
stop = true;
Thread.sleep(200);
System.out.println("main exit");
}

}

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

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

yield:可以用线程对象调用也可以用Thread对类调用,yield让出cpu的执行权给同等级线程,如果没有同等级的线程在等待          cpu,则该线程继续执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 多线程