终止线程的方法(这里的终止是指让线程停止执行):
1.stop():
使用Thread.stop()方法是强行终止线程,它会释放已经锁定的资源(即释放同步锁),但是会造成程序的不确定性。不推荐使用
例如:class User {
private String name ;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
synchronized public void printUser(String name,String pwd){//要求同时更新name,pwd
this.name=name;
this.pwd=pwd;
}
}
class MyThread extends Thread {
public void run() {
user.printUser("lili","123");
}
}
测试类:
public static void main(String[] args){MyThread mt=new MyThread();
mt.start();
lock.stop();
System.out.println(user.getName()+","+user.getPwd());
//此时程序执行具有不确定性,结果可能是 null null , lili null , lili 123
}
2.suspend():将一个线程挂起(暂停),resume()方法就是将一个挂起线程复活继续执行.suspend()方法不会释放同步锁,可能会造成死锁。例如线程A获取同步锁M的资源,线程A通过suspend()方法将线程挂起,接着线程B去访问互斥资源M,这时候就造成了死锁。
3.在run()方法中使用退出标志,使线程正常退出。
class MyThread extends Thread
{
public volatile boolean flag = true;
public void run()
{
while (flag); //do something
}
}
//测试类
public static void main(String[] args) throws Exception{
MyThread thread = new MyThread();
thread.start();
sleep(5000); // 主线程延迟5秒
thread.flag = false; // 终止线程thread
System.out.println("线程退出!");
}
}
4.使用interrupt方法中断线程:
使用interrupt方法来终端线程分为两种情况:
(1)线程处于阻塞状态(sleep(),wait(),join()),使用interrupt方法,将抛出一个InterruptedException。
class MyThread extends Thread
{
public void run()
{
try
{
sleep(50000); // 延迟50秒
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception
{
MyThread thread = new MyThread();
thread.start();
thread.interrupt();
}
}
(2)线程处于运行状态,使用while(!Thread.interrupted()){……}来判断线程是否被中断
在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法interrupted(),一个是非静态的方法isInterrupted()
interrupted() 方法是 static 的,用来测试当前线程是否已经是中断状态,具有清除中断状态的功能,所以第二次的时候返回值是 false。 isInterrupted() 方法并不是 static 的,用来测试线程对象是否是中断状态(该线程对象是指调用isInterrupted() 方法的线程对象)并且 isInterrupted() 方法并没有清除状态的功能,所以第二次的时候返回值是 true.