设置退出标识
除了正常结束外,还有哪些方式可以终止?
- 设置退出标识
package com.hexy.thread.demo;
public class ThreadDemo7 extends Thread{
//保证内存可见性
public volatile boolean exit = false;
@Override
public void run(){
while (!exit);
System.out.println("ThreadFlag线程退出");
}
public static void main(String[] args) throws InterruptedException {
ThreadDemo7 thread = new ThreadDemo7();
thread.start();
sleep(3000);
thread.exit = true;
thread.join();
System.out.println("线程退出");
}
}
- 中断的方式终止线程
1.Thread.join() 2.Thread.sleep() 3.ServerSocket.accept() 4.线程阻塞的情况下,设置退出标识没有用,需要用Thread的interrupt()方法
interrupt方法
package com.hexy.thread.demo;
public class ThreadDemo8 extends Thread{
volatile boolean exit = false;
@Override
public void run(){
while(!exit){
System.out.println(getName()+" is running");
try {
Thread.currentThread().join();
}catch (Exception e){
System.out.println("week up from block");
exit = true;
}
}
System.out.println(getName()+" is exitig");
}
public static void main(String[] args) throws InterruptedException {
ThreadDemo8 thread = new ThreadDemo8();
System.out.println("starting thread...");
thread.start();
Thread.sleep(3000);
System.out.println("Interrupt thread..." + thread.getName());
thread.exit = true;
//阻塞时退出阻塞状态
thread.interrupt();
Thread.sleep(3000);
System.out.println("stopping application");
}
}
废弃的方式
Thread.stop()就像拔掉计算机电源,强行释放子线程所持有的锁,导致被保护的资源出现线程安全问题- Thread.suspend() 使线程暂停,不会释放类似锁这样的资源/,Thread.resume()与suspend成套使用,使线程恢复,没成对出现容易死锁
- Runtime.runFinalizersOnExit,这个方法本身就线程不安全,可能导致(finalizers)终结器被活跃对象调用