class FirstThread extends Thread
{
//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程
public volatile boolean exit = false;
int count = 0;
public void run()
{
System.out.println(getName()+"is starting");
//执行run()方法前监测变量exit的值,若为true 则退出线程
while(!exit)
{
System.out.println(getName()+"is runing"+count++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(getName()+"即将从阻塞中退出");
System.out.println("this.isInterrupted()"+this.isInterrupted());
}
//使用条件退出线程
if(count == 10)
{
exit = true;
}
}
}
}
public class llp_java
{
public static void main(String[] args) throws InterruptedException
{
FirstThread thread1 = new FirstThread();
thread1.start();
//或在主函数中直接结束线程
thread1.exit = true;
System.out.println("线程退出");
}
}
结束非运行状态的线程:
如果线程调用了可中断等待方法,正处于等待状态,此时并是执行run()方法中的while循环,无法根据前面的全局变量的判定退出线程。此时可以通过调用Thread的interrupt方法让等待方法抛出InterruptedException异常,然后在循环外截获并处理异常,这样便跳出了线程run方法中的循环,以使线程顺利结束。使用方法如下:
class FirstThread extends Thread
{
//用关键字volatile设置变量为线程同步,即这个变量在某一个线程中被修改,其他地方的这个变量的值会被立即修改,这点在这里非常关键,能够在修改标识符时及时退出线程
public volatile boolean exit = false;
int count = 0;
public void interrupt()
{
//复写中断函数,改变exit的状态
exit = true;
}
public void run()
{
System.out.println(getName()+"is starting");
while(!exit)
{
System.out.println(getName()+"is runing"+count++);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//捕获阻塞中断后调用interrupted()函数,结束线程
Thread.interrupted();
System.out.println(getName()+"即将从阻塞中退出");
System.out.println("this.isInterrupted()"+this.isInterrupted());
}
//if(count == 10)
//{
// exit = true;
//}
}
}
}
public class llp_java
{
public static void main(String[] args) throws InterruptedException
{
FirstThread thread1 = new FirstThread();
thread1.start();
//直接调用中断函数,或者有阻塞中断发生时,会自动调用该函数
thread1.interrupt();
// thread1.join();
System.out.println("线程退出");
}