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();//插队
                }
            }
        }
    }
    
    刚刚参加工作,很有很多不懂不会的,发现错误,欢迎指正,谢谢!
  • 相关阅读:
    LGWR Trace Warning: Log Write Time ? Maybe not an issue
    Transaction & Undo
    XML Function at a glance
    Java step by step (1) : simple Spring IoC container
    First Impression on BBED: recover deleted rows
    【SQL*PLUS】Copy Command
    SYS_CONTEXT('USERENV', 'HOST') Return NULL & Oracle Fixed Tables
    ORA12519
    Some ORAs (32001, 00106)
    First Impression on BBED: explore block structure using map command
  • 原文地址:https://www.cnblogs.com/xd-study/p/13163206.html
Copyright © 2011-2022 走看看