1.使用状态位关闭正在运行的线程
class MyThread implements Runnable
{
private volatile boolean stop = false; //定义为volatile类型,避免使用缓存
public void setStop(boolean stop)
{
this.stop = stop;
}
public void run()
{
while (!stop)
{
System.out.println(Thread.currentThread().getName() + " is running");
}
System.out.println(Thread.currentThread().getName() + " is finished");
}
}
测试:
public class test {
public static void main(String[] args) throws InterruptedException{
MyThread mythread = new MyThread();
Thread thread = new Thread(mythread);
thread.start();
Thread.sleep(1000);
mythread.setStop(true);
}
}
结果为:
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is finished
使用这种方式需要注意每次循环都要判断状态
2.使用interrupt()关闭休眠阻塞线程
当线程等待某事件发生而被阻塞,此时是否能够使用状态标记呢?答案是否定的,因为线程被阻塞,那么他根本就得不到执行,也就不能检查状态变量,也就不能停止。 这种情况下可以使用interrupt()方法。
interrupt()只是把线程的状态改为中断状态,但是interrupt()方法只对执行了sleep()、wait()、join()方法而休眠的线程,使他们不再休眠,同时会抛出InterruptException异常
class MyThread implements Runnable
{
public void run()
{
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("已经被中断了");
}
System.out.println(Thread.currentThread().getName() + " is finished");
}
}
测试:
public class test {
public static void main(String[] args) throws InterruptedException{
MyThread mythread = new MyThread();
Thread thread = new Thread(mythread);
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
结果:
已经被中断了
Thread-0 is finished
中断之后会抛出异常,在catch中可以进行其他处理
3.关闭IO阻塞线程
对于io阻塞线程,java都会提供相应的关闭阻塞的办法。例如,一个网路应用程序可能要等待远端主机的相应,这个时候可以使用套接字close来关闭
class MyThread extends Thread
{
private ServerSocket server = null;
public void stopThread()
{
try
{
if (server != null)
{
server.close();
System.out.println("成功关闭");
}
}
catch (IOException e)
{
System.out.println("关闭出现异常");
}
}
public void run()
{
try
{
server = new ServerSocket(3333);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
测试:
public class test {
public static void main(String[] args) throws InterruptedException{
MyThread mythread = new MyThread();
mythread.start();
Thread.sleep(300);
mythread.stopThread();
}
}
结果为:
成功关闭