Java篇之多线程-03-线程状态

五大状态

在这里插入图片描述

在这里插入图片描述

线程方法

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

停止线程

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

/*
    1. 建议让线程正常停止:利用次数,不建议死循环
    2. 建议使用标志位:设置一个标志位 flag
    3. 不要使用 stop 或者 destroy 等过时或者 JDK 不建议使用的方法
 */
public class TestStop implements Runnable{
    // 1. 设置一个标志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        // 2. 使用该标识 flag
        while (flag) {
            System.out.println("threadRun..." + i++);
        }
    }

    // 3. 设置一个公开的方法停止线程,转换标志位
    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("mainRun..." + i);
            if (i == 900) {
                // 4. 调用自定义的stop方法,停止线程
                testStop.stop();
                System.out.println("线程已停止");
            }
        }
    }
}

线程休眠 sleep

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

// 模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable {
    // 票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <= 0) {
                break;
            }
            // 模拟延时
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 获取当前执行的线程名
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName + "--> 抢到了第" + ticketNums-- + "张票");
        }
    }

    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();

        // 一个对象被多个线程使用
        new Thread(ticket, "小明").start();
        new Thread(ticket, "小红").start();
        new Thread(ticket, "隔壁老王").start();
    }
}
package com.moon.state;

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep2 {
    public static void main(String[] args) {
        // 打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis()); // 获取当前系统时间
        while (true) {
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis()); // 更新当前时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}

线程礼让 yield

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让 CPU 重新调度,礼让不一定成功。看 CPU 心情~~
package com.moon.state;

// 礼让不一定成功~~
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield, "a").start();
        new Thread(myYield, "b").start();
    }
}

class MyYield implements Runnable {
    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + "线程开始执行");
        Thread.yield(); // 礼让
        System.out.println(threadName + "线程停止执行");
    }
}

线程强制执行 join

  • join 合并线程,待此线程执行完后,再执行其他线程,其他线程阻塞
  • 可以想象成插队
package com.moon.state;

// join 想象成插队
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 < 500; i++) {
            if (i == 100) {
                thread.join(); // 插队
            }
            System.out.println("main..." + i);
        }
    }
}

观测线程状态

Thread.State 线程状态

线程可以处于以下状态之一:

  • NEW
    尚未启动的线程处于此状态
  • RUNNABLE
    在Java虚拟机中执行的线程处于此状态
  • BLOCKED
    被阻塞等待监视器锁定的线程处于此状态
  • WAITING
    正在等待另一个线程执行特定动作的线程处于此状态
  • TIMED_WAITING
    正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
  • TERMINATED
    已退出的线程处于此状态

一个线程可以在给定时间点处于一个状态, 这些状态是不反映任何操作系统线程状态的虚拟机状态。

package com.moon.state;

// 观察线程状态
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            // 线程休眠 TIMED_WAITING
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            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(100);
            state = thread.getState(); // 更新线程状态
            System.out.println(state); // 输出状态
        }
    }
}

线程优先级

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

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是要看 CUP 的调度

package com.moon.state;

public class TestPriority {
    public static void main(String[] args) {
        // 打印主线程默认优先级 5
        printPriority();

        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority, "没有设置优先级");
        Thread t2 = new Thread(myPriority, "最小优先级");
        Thread t3 = new Thread(myPriority, "最大优先级");
        Thread t4 = new Thread(myPriority, "默认优先级");
        Thread t5 = new Thread(myPriority, "其他优先级");

        // 注意:先设置优先级,后启动

        t1.start(); //没有设置优先级,默认为 5

        // 最小
        t2.setPriority(Thread.MIN_PRIORITY); // Thread.MIN_PRIORITY = 1
        t2.start();

        // 最大
        t3.setPriority(Thread.MAX_PRIORITY); // Thread.MAX_PRIORITY = 10
        t3.start();

        // 默认
        t4.setPriority(Thread.NORM_PRIORITY); // Thread.NORM_PRIORITY = 5;
        t4.start();

        // 其他
        t5.setPriority(8);
        t5.start();
    }

    // 打印线程优先级
    public static void printPriority() {
        System.out.println(Thread.currentThread().getName() + " --> " + Thread.currentThread().getPriority());
    }
}

class MyPriority implements Runnable {
    @Override
    public void run() {
        TestPriority.printPriority();
    }
}

守护(daemon)线程

  • 线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
  • 如后台记录操作日志,监控内存,垃圾回收等~
package com.moon.state;

public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        Thread thread = new Thread(god);
        thread.setDaemon(true); // 默认是false表示为用户线程,正常的线程都是用户线程
        thread.start(); // 上帝 守护线程启动

        You you = new You();
        new Thread(you).start(); // 你 用户线程启动
    }
}

// 守护线程:上帝
// 虚拟机不用等待守护线程执行完毕
// 当用户线程执行完毕后,虽然守护线程还在执行一段时间,但虚拟机关闭后守护线程将终止
class God implements Runnable {
    @Override
    public void run() {
        while (true) {
            System.out.println("God blesses me");
        }
    }
}


// 用户线程:你
class You implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("Hello world");
        }
        System.out.println("=====Goodbye cruel world=====");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值