Java---21---停止线程

来源:互联网 发布:网络推广职位有哪些 编辑:程序博客网 时间:2024/06/07 12:49

停止线程

本来Thread类中有一个stop方法可以用来停止线程,但是却过时了,那么又该怎样停止线程呢?

线程运行其实运行的是run方法中的代码,那么只要将run方法停止,那么线程也就随之停止了。

一般线程的运行与循环相结合,那就好办了。将标记修改,那么run方法就会结束。

class StopThread implements Runnable {private boolean flag = true;public void run() {while (flag) {System.out.println(Thread.currentThread().getName() + "-----");}}public void changeFlag() {flag = false;}}public class Stop {public static void main(String[] args) {int num = 0;StopThread s = new StopThread();Thread t1 = new Thread(s);Thread t2 = new Thread(s);t1.start();t2.start();while (true) {if (num++ == 60) {s.changeFlag();break;}System.out.println("main");}}}

但是此方法却不适用于处于冻结状态。

当线程处于冻结状态的时候不会读取到标记,当然不会结束。

当没有指定的方式让冻结的线程恢复到运行状态时,需要对冻结进行清除,强制让线程恢复到运行状态下,这样就可以改变标记,从而让线程结束。

线程在同步中冻结了有怎么结束?Interrupt

API:

interrupt

public void interrupt()

中断线程。 

如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。 

如果线程在调用 Object 类的 wait()wait(long) 或 wait(long, int) 方法,或者该类的 join()join(long)join(long, int)sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。 

如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个 ClosedByInterruptException。 

如果该线程在一个 Selector 中受阻,则该线程的中断状态将被设置,它将立即从选择操作返回,并可能带有一个非零值,就好像调用了选择器的 wakeup 方法一样。 

如果以前的条件都没有保存,则该线程的中断状态将被设置。

中断一个不处于活动状态的线程不需要任何作用。 

抛出: 

SecurityException - 如果当前线程无法修改该线程

class StopThread implements Runnable {private boolean flag = true;public synchronized void run() {while (flag) {try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch block// e.printStackTrace();System.out.println("Exception");}System.out.println(Thread.currentThread().getName() + "-----");}}public void changeFlag() {flag = false;}}public class Stop {public static void main(String[] args) {int num = 0;StopThread s = new StopThread();Thread t1 = new Thread(s);Thread t2 = new Thread(s);t1.start();t2.start();while (true) {if (num++ == 60) {// s.changeFlag ();t1.interrupt();t2.interrupt();break;}System.out.println("main");}}}

通过调用interrupt方法,这时线程已经从冻结状态恢复到了运行状态,但是只运行了一次。

使用interrupt会抛出异常,在异常抛出的同时,改变状态,就可以让线程停止。


class StopThread implements Runnable {private boolean flag = true;public synchronized void run() {while (flag) {try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch block// e.printStackTrace();System.out.println("Exception");flag = false;}System.out.println(Thread.currentThread().getName() + "-----");}}public void changeFlag() {flag = false;}}public class Stop {public static void main(String[] args) {int num = 0;StopThread s = new StopThread();Thread t1 = new Thread(s);Thread t2 = new Thread(s);t1.start();t2.start();while (true) {if (num++ == 60) {// s.changeFlag ();t1.interrupt();t2.interrupt();break;}System.out.println("main");}}}







1 0
原创粉丝点击