• 二、线程常用方法


    二、线程常用方法

    1、常用方法

    修饰符和类型方法描述
    public longgetId()返回此线程的标识符
    public final StringgetName()返回此线程的名称
    public final synchronized voidsetName(String name)将此线程的名称更改为等于参数 name
    public Thread.StategetState()返回此线程的状态
    public final voidsetPriority(int newPriority)更改此线程的优先级
    public final intgetPriority()返回此线程的优先级
    public static native voidsleep(long millis)使当前正在执行的线程以指定的毫
    秒数暂停(暂时停止执行),具体
    取决于系统定时器和调度程序的精
    度和准确性
    public final synchronized voidjoin()等待这个线程死亡
    (就是霸道插队直到运行结束)
    public static native voidyield()对调度程序的一个暗示,即当前线
    程愿意产生当前使用的处理器
    public voidinterrupt()中断这个线程(不推荐这种方式)
    public final native booleanisAlive()测试这个线程是否活着

    2、join

    来看一下官方的解释:Waits for this thread to die.

    就问你霸不霸道?!!!

    1、CODE

    package mii.thread.demo10线程5大状态;
    /**
     * 测试插队:join
     */
    public class TestJoin implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println("线程VIP来了" + i);
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            TestJoin tj = new TestJoin();
    
            // 启动我们的线程
            Thread thread = new Thread(tj);
            thread.start();
            
            // 主线程
            for (int i = 0; i < 10; i++) {
                if(i == 5){
                    thread.join(); // 插队
                }
                System.out.println("main--" + i);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    2、Result

    在这里插入图片描述


    3、sleep

    • sleep(毫秒) 指定当前线程阻塞的毫秒数
    • sleep 存在异常 InterruptedException 需要捕获或抛出
    • sleep 时间结束后线程进入就绪状态,继续参与 CPU 调度的竞争
    • 每个对象都有一个锁,sleep 不会释放锁

    1、CODE

    package mii.thread.demo10线程5大状态;
    /**
     * 模拟倒计时
     */
    public class TestSleep02 {
        public static void main(String[] args) throws InterruptedException {
            int i = 10;
            while(i >= 0){
                System.out.println(i--);
                Thread.sleep(1000);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、Result

    在这里插入图片描述


    3、线程停止

    • 建议线程正常停止(利用次数,不建议死循环)
    • 建议使用标志位(设置一个标志位flag)
    • 不要使用 stopdestory等过时或JDK不建议使用的方法

    1、CODE

    package mii.thread.demo10线程5大状态;
    /**
     * 测试停止:stop
     * 1、建议线程正常停止(利用次数,不建议死循环)
     * 2、建议使用标志位(设置一个标志位flag)
     * 3、不要使用stop或destory等过时或JDK不建议使用的方法
     */
    public class TestStop implements Runnable{
        // 1、设置一个标志位
        private boolean flag = true;
    
        @Override
        public void run() {
            int i = 0;
            while(flag){
                System.out.println("run...Thread-->" + i++);
            }
        }
    
        // 2、设置一个公开方法停止线程,转换标志位
        public void stop(){
            this.flag = false;
        }
    
        public static void main(String[] args) {
            TestStop ts = new TestStop();
    
            new Thread(ts).start();
    
            for (int i = 0; i < 20; i++) {
                System.out.println("main...time-->" + i);
                if(i == 9){
                    // 调用自己写的stop方法切换标志位,停止线程
                    ts.stop();
                    System.out.println("线程该停止了!");
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    2、Result

    在这里插入图片描述


    4、yield

    • 线程礼让,让当前正在执行的线程暂停,但不阻塞
    • 线程从运行状态转为就绪状态
    • 让 CPU 重新调度,礼让不一定成功,全看 CPU 心情

    1、CODE

    package mii.thread.demo10线程5大状态;
    /**
     * 测试礼让:yield
     * 礼让不一定成功,看CPU心情
     */
    public class TestYield implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "线程开始执行");
            Thread.yield(); // 礼让
            System.out.println(Thread.currentThread().getName() + "线程停止执行");
        }
    
        public static void main(String[] args) {
            TestYield ty = new TestYield();
    
            new Thread(ty, "A").start();
            new Thread(ty, "B").start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    2、Result

    在这里插入图片描述


    5、线程优先级 Priority

    • Java 提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行(优先级高低只影响被调用的概率,不是说优先级高就先执行,依然会出现性能倒置的情况,完全看 CPU 心情)

    • 线程的优先级用数字表示,范围从1~10

    • /** 线程可以具有的最小优先级. */
      public final static int MIN_PRIORITY = 1;
      
      /* 分配给线程的默认优先级. */
      public final static int NORM_PRIORITY = 5;
      
      /* 线程可以具有的最大优先级. */
      public final static int MAX_PRIORITY = 10; 
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    • 使用以下方式改变或获取优先级

    • /* 修改此线程的优先级. */
      public final void setPriority(int newPriority) {
          ThreadGroup g;
          checkAccess();
          if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
              throw new IllegalArgumentException();
          }
          if((g = getThreadGroup()) != null) {
              if (newPriority > g.getMaxPriority()) {
                  newPriority = g.getMaxPriority();
              }
              setPriority0(priority = newPriority);
          }
      }
      
      /* 返回此线程的优先级. */
      public final int getPriority() {
          return priority;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19

    1、CODE

    package mii.thread.demo11线程优先级;
    
    /**
     * 测试线程优先级:priority
     */
    public class TestPriority {
        public static void main(String[] args) {
            // 打印主线程优先级
            System.out.println(Thread.currentThread().getName() + "--->" +
                               Thread.currentThread().getPriority());
    
            Thread thread0 = new Thread(()->
                  System.out.println(Thread.currentThread().getName() + "--->" +
                                     Thread.currentThread().getPriority()));
            Thread thread1 = new Thread(()->
                  System.out.println(Thread.currentThread().getName() + "--->" +
                                     Thread.currentThread().getPriority()));
            Thread thread2 = new Thread(()->
                  System.out.println(Thread.currentThread().getName() + "--->" +
                                     Thread.currentThread().getPriority()));
            Thread thread3 = new Thread(()->
                  System.out.println(Thread.currentThread().getName() + "--->" +
                                     Thread.currentThread().getPriority()));
            // 先设置优先级再启动
            thread1.setPriority(1);
            thread2.setPriority(4);
            thread3.setPriority(Thread.MAX_PRIORITY);
            thread0.start();
            thread1.start();
            thread2.start();
            thread3.start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    2、Result

    在这里插入图片描述

  • 相关阅读:
    《基层女性》摘录
    java中 得到两个数组中不同的元素 有效
    云原生核心技术(一文搞懂云原生)
    gitee 使用
    毫末速度:中国自动驾驶落地最快的1000天
    JVM本地方法栈介绍
    mac pro M1(ARM)安装:安装zookeeper可视化工具PrettyZoo、ZooKeeperAssistant
    MySQL(十三)binglog 和 redo log
    不是跨域访问权限_而是后台代码错误_错误一点点排
    【Java】SpringBoot应用简单示例
  • 原文地址:https://blog.csdn.net/qq_30769437/article/details/126437115