当前位置: 移动技术网 > IT编程>开发语言>Java > java 停止线程

java 停止线程

2020年04月01日  | 移动技术网IT编程  | 我要评论

隐世灵医,莫洛西亚共和国,宬人电影在线观看

stop()已经过时.

停止线程:run()方法结束。

开启多线程运行,通常代码都是循环结构。

只要控制住循环,就可以让run()结束,也就结束了线程。

class stopthread implements runnable {
    private boolean flag = true;

    @override
    public void run() {
        while (flag) {
            system.out.println(thread.currentthread().getname() + "...run");
        }
    }

    public void changeflag() {
        flag = false;
    }
}

public class stopthreaddemo {
    public static void main(string[] args) {
        stopthread st = new stopthread();
        thread t1 = new thread(st);
        thread t2 = new thread(st);
        t1.start();
        t2.start();
        int num = 0;
        while (true) {
            if (num++ == 60) {
                st.changeflag();
                break;
            }
            system.out.println(thread.currentthread().getname() + "......" + num);
        }
    }
}

 

特殊情况:当线程处于冻结状态就不会读取到标记,那么线程也就不会结束。

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

thread类中提供了该方法:interrupt();

class stopthread implements runnable {
    private boolean flag = true;

    @override
    public synchronized void run() {
        while (flag) {
            try {
                wait();
            } catch (interruptedexception e) {
                system.out.println(thread.currentthread().getname() + "...exception");
                flag = false;
            }
            system.out.println(thread.currentthread().getname() + "...run");
        }
    }

    public void changeflag() {
        flag = false;
    }
}

public class stopthreaddemo {
    public static void main(string[] args) {
        stopthread st = new stopthread();
        thread t1 = new thread(st);
        thread t2 = new thread(st);
        t1.start();
        t2.start();
        int num = 0;
        while (true) {
            if (num++ == 60) {
//                st.changeflag();
                t1.interrupt();
                t2.interrupt();
                break;
            }
            system.out.println(thread.currentthread().getname() + "......" + num);
        }
        system.out.println("over");
    }
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网