线程几种方法

来源:互联网 发布:库克和乔布斯 知乎 编辑:程序博客网 时间: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



0 0
原创粉丝点击