zoukankan      html  css  js  c++  java
  • 42. 线程停止

    一般我们使用多线程的时候,一般都会使用循环,毕竟如果就一个语句,没必要使用多线程

    那么怎样停止一个线程呢?

    线程停止无外乎2种,要么是执行完了任务,要么强制停止

    线程的停止:

        1.我们可以定义一个boolean类型的变量结合notity方法去控制线程的停止(使用notity是为了防止要被停止的线程wait)

        2.也可以使用interrupt方法(强制停止会让wait方法抛异常),至于start方法淘汰了,不建议使用

    下面是两种方式让线程停止的例子:

      方式一例子:

    public class Demo10 implements Runnable{
        boolean flas = true;
        @Override
        public void run() {
            while(flas) {
                synchronized (this) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName());
            }
            
        }
        public static void main(String[] args) {
            Demo10 d = new Demo10();
            Thread thread = new Thread(d,"狗娃");
            thread.start();
            for (int i = 0; i < 100; i++) {
                //如果主线程的i=80的时候,停止狗娃线程
                if(i==20) {
                    d.flas = false;
                    synchronized (d) {
                        d.notify();
                    }
                }
                System.out.println(Thread.currentThread().getName()+i);
            }
        }
    }

    方式二:例子2

    public class Demo10 implements Runnable{
        boolean flas = true;
        @Override
        public void run() {
            while(flas) {
                synchronized (this) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        System.out.println("抛异常");
                    }
                }
                System.out.println(Thread.currentThread().getName());
            }
            
        }
        public static void main(String[] args) {
            Demo10 d = new Demo10();
            Thread thread = new Thread(d,"狗娃");
            thread.start();
            for (int i = 0; i < 100; i++) {
                //如果主线程的i=80的时候,停止狗娃线程
                if(i==20) {
                    d.flas = false;
                    thread.interrupt();//强制停止指定线程
                }
                System.out.println(Thread.currentThread().getName()+i);
            }
        }
    }

     注意:这两个例子会出现过了20后,还会出现一次狗娃线程输出的语句

      应该是狗娃线程刚判断是true后还没来得急执行输出语句,cpu就被main线程强去了,才导致后面还会执行一次(不过线程是真的停止了)

     也有可能是wait造成的(去掉了也可能出现这种情况,毕竟我们没有用锁)

  • 相关阅读:
    Jzoj4822 完美标号
    Jzoj4822 完美标号
    Jzoj4792 整除
    Jzoj4792 整除
    Educational Codeforces Round 79 A. New Year Garland
    Good Bye 2019 C. Make Good
    ?Good Bye 2019 B. Interesting Subarray
    Good Bye 2019 A. Card Game
    力扣算法题—088扰乱字符串【二叉树】
    力扣算法题—086分隔链表
  • 原文地址:https://www.cnblogs.com/zjdbk/p/8971230.html
Copyright © 2011-2022 走看看