zoukankan      html  css  js  c++  java
  • 线程的停止,礼让,以及插队

    线程停止

    public class TestStop implements Runnable {
    
        //1.设置一个标志位
        private boolean flag = true;
        @Override
        public void run() {
            int i = 0;
            while (flag){
                System.out.println("Thread is running..." + i);
            }
        }
    
        //2.设置一个公开的方法停止线程,转换标志位
        public void stop(){
            this.flag = false;
        }
    
        public static void main(String[] args) {
            TestStop testStop = new TestStop();
            new Thread(testStop).start();
            for (int i = 0; i < 1000; i++) {
                System.out.println("main" + i);
                if (i == 900){
                    //调用stop方法,切换标志位,停止线程
                    testStop.stop();
                    System.out.println("该线程该停止了");
                }
            }
    
        }
    }
    

    建议:

    1.建议线程正常停止--->利用次数不建议使用死循环
    2.建议使用标志位--->设置一个标志位
    3.不要使用stop或destroy等过时或者JDK不建议的方法
    

    线程优先级

    public class TestYield {
        public static void main(String[] args) {
            MyYield myYield = new MyYield();
            Thread a = new Thread(myYield, "a");
            a.start();
            Thread b = new Thread(myYield, "b");
            b.start();
        }
    }
    class MyYield implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "开始");
            Thread.yield();//线程礼让
            System.out.println(Thread.currentThread().getName() + "结束");
        }
    }
    

    yield方法只是让出cpu,之后可能会再次进入cpu,故礼让不一定成功!

    线程强制执行

    public class TestJoin implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("我是vip线程,第" + i +"次");
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            TestJoin testJoin = new TestJoin();
            Thread thread = new Thread(testJoin);
            thread.start();
            for (int i = 0; i < 200; i++) {
                System.out.println("我是主线程,第" + i +"次");
                if (i == 99){
                    thread.join();//插队
                }
            }
        }
    }
    
    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    Bug测试报告--在线考试系统--金州勇士
    Bug测试报告--食物链教学工具--奋斗吧兄弟
    Jquery对象和dom对象获取html的方法
    mysql中常见的存储引擎和索引类型
    转:spring MVC HTTP406 Not Acceptable
    Mybatis动态建表
    ssm框架插入mysql数据库中文乱码问题解决
    Maven环境下Poi的使用
    【转】Mybatis传多个参数(三种解决方案)
    【译文】用Spring Cloud和Docker搭建微服务平台
  • 原文地址:https://www.cnblogs.com/xd-study/p/13163206.html
Copyright © 2011-2022 走看看