多线程之interrupted与isInterrupted

interrupt()

暂停线程方法interrupt(); 但是调用interrupt()并不是马上就停止,只是标记

判断线程是否中断 this.interrupted(); this.isInterrupted();

interrupted()和isInterrupted()

this.interrupted():测试当前线程是否中断,当前指运行this.interrupted()的线程.内部实现是调用的当前线程的isInterrupted()

this.isInterrupted():测试线程是否中断.内部是调用该方法的对象所表示的那个线程的isInterrupted()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

public class MyThread extends Thread {

public static void main(String[] args) throws InterruptedException {
MyThread thread=new MyThread();
thread.start();
Thread.sleep(1000);
thread.interrupt();
System.out.println(thread.isInterrupted());
}

@Override
public void run() {
int i=0;
System.out.println(i++);
}
}
结果:
0
false
由此结果都是false可知Thread调用interrupt()并不是马上就使线程暂停

注意,如果线程已中断 连续两次调用Thread.interrupted();
第一个是ture, 但是第二个是 false, 因为第一次调用后已经清除其中断的状态。
但是this.isInterrupted()不会清除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
	 public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());
}
结果
true
false
public class MyThread_1 extends Thread{

public static void main(String[] args) {
MyThread_1 thread_1=new MyThread_1();
thread_1.start();
thread_1.interrupt();
System.out.println(thread_1.isInterrupted());
System.out.println(thread_1.isInterrupted());
}

@Override
public void run() {
System.out.println("run....");
}
}
结果
true
true
run....

-------------本文结束感谢您的阅读-------------