线程几种方法
来源:互联网 发布:库克和乔布斯 知乎 编辑:程序博客网 时间:2024/05/21 08:59
1. isAlive():判断当前的线程是否处于活动状态
活动状态是指线程已经启动且尚未终止。
public class IsAliveTest extends Thread {
public static void main(String[] args) {
IsAliveTest it=new IsAliveTest();
System.out.println("begin="+it.isAlive());
it.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("end="+it.isAlive());
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("run="+this.isAlive());
}
}
运行结果:
begin=false
run=true
end=false
2. sleep()方法:在指定的毫秒数内让当前 正在执行的线程 休眠。正在执行的线程 指的是 this.currentThread()返回的线程。
3.getId()方法:取得线程的唯一标识。
4.停止线程:在线程处理完任务之前停掉正在做的操作。
停止线程可以使用Thread.stop()方法,但是它是不安全的,也是已经被弃用的。大多数停止一个线程的操作使用Thread.interrupt()方法,但是这个方法需要加入一个判断才可以完成线程的停止。
Java中的三种终止正在运行的线程的方法:
(1)使用退出标志,使线程正常退出,也就是当run()方法完成后线程自动终止。
(2)使用stop()方法,但是这个方法是已经作废的,也是不安全的。
(3)使用interrupt()方法中断线程。
Thread.java中提供了两种方法来判断线程的状态是不是停止的:
(1)this.interrupted():测试当前线程是否已经中断。执行后线程的中断状态由该方法清除。此方法的声明是静态的
(2)this.isInterrupted():测试线程是否已经中断。但是不清除状态标识。此方法的声明不是静态的
interrupted代码段1:
public class InterruptTest extends Thread{
public static void main(String[] args) {
try {
InterruptTest it=new InterruptTest();
it.start();
Thread.sleep(1000);
it.interrupt();
System.out.println("是否停止1?="+it.interrupted());
System.out.println("是否停止2?="+it.interrupted());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("end");
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
for (int i = 0; i <2000; i++) {
System.out.println("i="+(i+1));
}
}
}
部分输出结果:
i=1998
i=1999
i=2000
是否停止1?=false
是否停止2?=false
end
从输出的结果来看,线程并没有终止,说明 interrupted()方法测试的当前线程。上面程序中当前线程是main,它从未产生中断,所以结果都为false。
interrupted代码段2:使产生中断
Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());
此段代码运行后结果会是一个true和false.这是因为interrupted()方法具有清除状态的功能
isInterrupted代码段:
Thread t=Thread.currentThread();
t.interrupt();
System.out.println(t.isInterrupted());
System.out.println(t.isInterrupted());
运行部分结果:
true
true
- 线程几种方法
- 线程几种方法
- 几种方法实现线程
- 实现线程同步的几种方法
- 创建一个线程几种方法
- C#线程同步的几种方法
- C#线程同步的几种方法
- C#线程同步的几种方法
- C#线程同步的几种方法
- C#线程同步的几种方法
- 线程退出的几种方法
- C#启动线程的几种方法
- C#线程同步的几种方法
- Map线程安全几种实现方法
- 线程同步的几种方法
- 线程同步的几种方法
- Map线程安全几种实现方法
- C#线程同步的几种方法
- winpc下Mac10.11+Vmware12
- Oracle脚本工具1.0
- Python 安装 第三方库的安装技巧
- 全部清除告警后导致主界面告警数和告警界面告警数不一致
- 【BestCoder Round #59 (div.1) B】【疯狂的火神】
- 线程几种方法
- 由 mysql 存储过程无法调用引起的一串问题
- 个人记录-LeetCode 1.Two Sum
- Linux 初体验
- Could not obtain transaction-synchronized Session for current thread
- Android PLT/GOT 符号重定向过程
- RequireJS和AMD规范
- Annotation学习笔记
- jQuery 中 attr() 和 prop() 方法的区别