• Java多线程探究【二线程状态】


    🐞线程状态🐞

    • 创建状态
    • 就绪状态
    • 阻塞状态
    • 运行状态
    • 死亡状态
      在这里插入图片描述
      在这里插入图片描述

    1.1 🐦线程方法🐦

    方法说明
    setPriority(int newPriority)更改线程的优先级
    static void sleep(long millis在指定的毫秒数内让当前正在执行的线程休眠
    void join()等待该线程终止
    staticvoidyield()暂停当前正在执行的线程对象,并执行其他线程
    void interrupt()中断线程,别用这个方式
    boolean isAlive()测试线程是否处于活动状态

    1.2 🐳停止线程🐳

    • 不推荐使用JDK提供的stop()、destroy()方法【已废弃】
    • 推荐线程自己停下来,建议使用一个标志位进行终止,当flag=false,则终止线程运行

    1.2.1 🍁栗子🍁

    /**
     * @author 缘友一世
     * date 2022/11/11-17:20
     */
    public class TestStop implements Runnable {
        private boolean flag = true;//1 标志位
    
        @Override
        public void run() {
            int i = 1;
            while (flag) {
                System.out.println("run...Thread" + i++);
            }
        }
        //设置一个公开的方法改变标志位,停止线程
        public void stop() {
            this.flag=!flag;
        }
    
        public static void main(String[] args) {
            TestStop testStop = new TestStop();
            new Thread(testStop).start();
           for(int i=1;i<=100;i++) {
               System.out.println("main"+i);
               if(i==5) {//将停止的循环条件尽量设置的靠前一些,因为主线程执行的非常快,
                   // 有可能自定义线程,还没来得及停止,主线程就已经执行结束了
                   //调用停止线程的方法,改变标志位
                   testStop.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

    在这里插入图片描述

    1.3 🐊线程休眠🐊

    • sleep(时间)指定当前线程阻塞的毫秒数。
    • sleep存在异常InterruptedException;
    • sleep时间达到后线程进入就绪状态
    • sleep可以模拟网络延时、倒计时等
    • 每一个对象都有一个锁,sleep不会释放锁

    1.3.1 🪰模拟网络延时🪰

    /**
     * @author 缘友一世
     * date 2022/11/11-17:38
     */
    //模拟网络延时
    public class TestSleep implements Runnable{
        private int ticketNum=10;
        @Override
        public void run() {
            while(true) {
                if(ticketNum==0) {
                    break;
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNum--+"张票");
            }
        }
    
        public static void main(String[] args) {
            TestSleep testSleep = new TestSleep();
            new Thread(new TestSleep(),"小王").start();
            new Thread(new TestSleep(),"小李").start();
            new Thread(new TestSleep(),"小张").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

    在这里插入图片描述

    • 在这里,我们就隐约感受到并发问题

    1.3.2 🦞显示时间🦞

    /**
     * @author 缘友一世
     * date 2022/11/11-17:49
     */
    //输出时间
    public class TestCountdown {
        public static void main(String[] args) throws InterruptedException {
            Date date = new Date(System.currentTimeMillis());
            while (true) {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
                date=new Date(System.currentTimeMillis());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    在这里插入图片描述

    1.3.3 🦄模拟倒计时🦄

    /**
     * @author 缘友一世
     * date 2022/11/11-17:49
     */
    //模拟倒计时
    public class TestCountdown {
        public static void main(String[] args) throws InterruptedException {
            TimeDown();
        }
        public static void TimeDown() throws InterruptedException {
            int num=10;
            while(true) {
                if(num==0) break;
                Thread.sleep(1000);
                System.out.println(num--);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    1.4 🦀线程礼让🦀

    • 礼让线程,让当前正在执行的线程暂停,但不阻塞
    • 将线程从运行状态转为就绪状态
    • 让cpu重新调度,礼让不一定成功!因为最终的调度由cpu决定

    1.4.1 🤬栗子🤬

    /**
     * @author 缘友一世
     * date 2022/11/11-19:38
     */
    //礼让线程,礼让cpu不一定接受
    public class TestYield {
        public static void main(String[] args) {
            MyYield myYield = new MyYield();
            new Thread(myYield,"a1").start();
            new Thread(myYield,"a2").start();
        }
    }
    class MyYield implements Runnable {
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"线程开始执行");
            Thread.yield();//礼让
            System.out.println(Thread.currentThread().getName()+"线程停止执行");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述
    在这里插入图片描述

    1.5 🕸️线程合并🕸️

    • Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞【就是进行排队】

    1.5.1 🕷️栗子🕷️

    /**
     * @author 缘友一世
     * date 2022/11/11-19:46
     */
    public class TestJoin implements Runnable{
    
        public static void main(String[] args) throws InterruptedException {
            //启动线程
            TestJoin testJoin = new TestJoin();
            Thread thread = new Thread(testJoin);
            thread.start();
            //设置主线程
            for(int i=1;i<=8;i++) {
                if(i==3) {
                    thread.join();
                }
                System.out.println("普通主线程"+i);
            }
        }
    
        @Override
        public void run() {
            for(int i=1;i<=3;i++) {
                System.out.println("vip用户线程来了"+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

    在这里插入图片描述

    1.6 🦜线程状态观测🦜

    • Thread.State
    状态说明
    NEW尚未启动的线程处于此状态。
    RUNNABLE在Java虚拟机中执行的线程处于此状态
    BLOCKED被阻塞等待监视器锁定的线程处于此状态
    WAITING正在等待另一个线程执行特定动作的线程处于此状态。
    TIME_DWAITING正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
    TERMINATED已退出的线程处于此状态。
    • 🪶一个线程可以在给定时间点处于一个状态,这些状态是不反映任何操作系统状态的虚拟机状态。🪶

    1.6.1 💎栗子💎

    /**
     * @author 缘友一世
     * date 2022/11/11-19:59
     */
    public class TestState {
        public static void main(String[] args) throws InterruptedException {
            Thread thread = new Thread(()->{
                for(int i=1;i<5;i++) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.println("===");
            });
    
            //观察状态
            Thread.State state = thread.getState();
            System.out.println(state);//new
    
            //观察启动线程启动后的状态
            thread.start();//启动线程
            state=thread.getState();//要及时更新状态
            System.out.println(state);//runnable
    
            //TERMINATED--终止
            //之线程不终止,就一直输出状态
            while (state!=Thread.State.TERMINATED) {
                Thread.sleep(10);
                state=thread.getState();
                System.out.println(state);//TIMED_WAITING
            }
        }
    }
    
    
    • 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

    在这里插入图片描述

    1.7 🦟程序的优先级【学了个寂寞】🦟

    • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程线程调度器按照优先级决定应该调度哪个线程来执行
    • 线程的优先级用数字表示,范围从1~10。
      • Thread.MIN_PRIORITY= 1;
      • Thread.MAX_PRIORITY= 10
      • Thread.NORM_PRIORITY=5;
    • 使用以下方式改变或获取优先级
      • getPriority().setPriority(int XXX)

    1.7.1 🐟栗子🐟

    
    /**
     * @author 缘友一世
     * date 2022/11/11-20:19
     */
    public class TestPriority{
        public static void main(String[] args) {//main线程优先级默认为5
            System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
            MyPriority myPriority = new MyPriority();
            Thread thread1 = new Thread(myPriority);
            Thread thread2 = new Thread(myPriority);
            Thread thread3 = new Thread(myPriority);
            Thread thread4 = new Thread(myPriority);
            Thread thread5 = new Thread(myPriority);
            Thread thread6 = new Thread(myPriority);
            Thread thread7 = new Thread(myPriority);
            Thread thread8 = new Thread(myPriority);
    
            //设置一些优先级 1~10
            thread1.start();
    
            thread2.setPriority(4);
            thread2.start();
    
            thread3.setPriority(7);
            thread3.start();
    
            thread7.setPriority(3);
            thread7.start();
    
            thread8.setPriority(Thread.MAX_PRIORITY);
            thread8.start();
    
            thread5.setPriority(6);
            thread5.start();
        }
    }
    class MyPriority implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        }
    
    }
    
    
    • 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
    • 41
    • 42
    • 43
    • 44
    • 45

    在这里插入图片描述

    • 即使设置了线程的优先级,一样无法确保这个线程一定先执行,因为它有很大的随机性。它并无法控制执行哪个线程,因为线程的执行,是抢占资源后才能执行的操作,而抢点资源时,最多是给于线程优先级较高的线程一点机会而已,能不能抓住可是不一定的。
    • 线程优化级较高的线程不一定先执行。线程的执行顺序真正取决于CPU调度器(在Java中是JVM来调度),程序员无法控制。

    1.8 🐬守护(daemon)线程🐬

    • 线程分为用户线程和守护线程。如:main()
    • 虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕。如gc(),后台记录操作日志、监控内存、垃圾回收

    1.8.1 🐠栗子🐠

    /**
     * @author 缘友一世
     * date 2022/11/11-20:50
     */
    public class TestDaemon {
        public static void main(String[] args) {
            Teacher teacher = new Teacher();
            Student student = new Student();
    
            //用户线程启动
            new Thread(student).start();
            Thread thread = new Thread(teacher);
            //默认是false,表示用户线程;true 守护线程
            thread.setDaemon(true);
            //守护线程启动
            thread.start();
        }
    }
    class Teacher implements Runnable {
    
        @Override
        public void run() {
           while(true)  {
                System.out.println("老师在认真讲课");
            }
        }
    }
    class Student implements Runnable {
        @Override
        public void run() {
            System.out.println("上课了");
            for(int i=1;i<=5;i++) {
                System.out.println("上课中,已过"+i+"分钟");
            }
            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

    在这里插入图片描述

  • 相关阅读:
    科普:什么是ChatGPT?(文末有彩蛋)
    详谈判断点在多边形内的七种方法
    vue 使用Dialog对话框使用过程中出现灰色遮罩问题
    SVM模型实现人脸识别
    批处理小程序的制作
    strings.xml补充知识
    Vue element-ui表格嵌进度条
    JVM 基本概念
    mobaxterm会话同步
    深度学习-偏导数复习
  • 原文地址:https://blog.csdn.net/yang2330648064/article/details/127809668