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

[置顶] Java 多线程学习笔记 (一)interrupt

2016-07-03 15:33 691 查看
Java 多线程怎么停止线程?

本示例将调用interrupt()方法来停止线程,但是interrupt()方法的使用效果并不像 for+break 语句那样,马上就停止循环。调用interrupt()方法仅仅是在当前线程中打了一个停止标记,并不是真的停止线程。

拓展,先来了解两个方法

1.interrupted()测试当前线程是否已经中断

package test;

import exthread.MyThread;

import exthread.MyThread;

public class Run2 {
public static void main(String[] args) {
Thread.currentThread().interrupt();
System.out.println("是否停止1?=" + Thread.interrupted());
System.out.println("是否停止2?=" + Thread.interrupted());
System.out.println("end!");
}
}


运行结果:

是否停止1?=true

是否停止2?=false

end!  

jdk中说明:如果程序两次调用interrupted()方法的话。第二次的结果为false;

2.isinterrupted()  

package test;

import exthread.MyThread;

import exthread.MyThread;

public class Run3 {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(100);
thread.interrupt();
System.out.println("是否停止1?="+thread.isInterrupted());
System.out.println("是否停止2?="+thread.isInterrupted());
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}


运行结果:

是否停止1?=true

是否停止2?=true

两种方法的区别:

1.检查当前线程是否打上了中断标记  执行两次第二次的时候清除标记

2.第二个方法检查线程Thread对象是否打上了中断标记  执行两次不清除标记
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: