Java 线程运行方法和原理

线程运行

原理

栈与栈帧:

Java 虚拟机栈会为每个启动的线程分配一块栈内存,其中存储着栈帧(Frame)

  • 每个栈由多个栈帧组成,栈帧对应调用方法(函数)所占用的内存
  • 每个栈只有一个活动栈,对应当前正在执行的方法

单线程示例:

main, method1, method2 各自对应这一个栈帧,存储在一个栈中:

在这里插入图片描述

public class d1_Frame {
    public static void main(String[] args) {
        method1(10); // 调用method1
    }

    public static void method1(int x){
        int y = x + 1;
        Object obj = method2(); // 调用 method2
    }
    public static Object method2(){
        Object obj = new Object();
        return obj;
    }
}

在这里插入图片描述

多线程示例:

包含两个线程 maint1 ,分别创建两个独立的栈,每个栈里包含各自的栈帧

main线程的栈:

xxx

t1 线程的栈:

xxx

public class d1_Frame {
    public static void main(String[] args) {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                method1(20); // t1 线程调用 method1
            }
        };
        t1.setName("t1");
        t1.start();
        method1(10); // main 调用method1
    }

    public static void method1(int x){
        int y = x + 1;
        Object obj = method2(); // 调用 method2
    }
    public static Object method2(){
        Object obj = new Object();
        return obj;
    }
}

线程上下文切换(Thread Context Switch)

线程上下文切换是指:CPU不再执行当前线程,转而执行其他线程的代码的过程

发生 Context Switch 的原因:

  • 线程的 cpu 时间片用完
  • 垃圾回收
  • 有更高优先级的线程需要运行
  • 线程自己调用了 sleep、yield、wait、join、park、synchronized、lock 等方法

当 Context Switch 发生时,需要由操作系统保存当前线程的状态,并恢复另一个线程的状态,Java 中对应的概念
就是程序计数器(Program Counter Register),它的作用是记住下一条 jvm 指令的执行地址,是线程私有的

  • 状态包括程序计数器、虚拟机栈中每个栈帧的信息,如局部变量、操作数栈、返回地址等
  • Context Switch 频繁发生会影响性能

线程运行的常见方法

xx

run与start

run调用:直接调用 run 方法,则是 main 主线程执行的,并没有创建一个新线程执行

start调用:创建一个新的线程 t1t1 线程与 main 线程是同时进行的。调用后,线程的状态也会发生改变

@Slf4j(topic = "c.d2_run_start")
public class d2_run_start {
    public static void main(String[] args) {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("running");
            }
        };

        t1.run();
        // 14:25:50 [main] c.d2_run_start - running
        System.out.println(t1.getState()); //NEW

        t1.start();
        // 14:28:11 [t1] c.d2_run_start - running
        System.out.println(t1.getState()); // RUNNABLE
    }
}

sleep

  1. sleep 的对线程状态的影响:调用 sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
@Slf4j(topic = "c.d3_sleep_yield")
public class d3_sleep_yield {
    public static void main(String[] args) {
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                log.debug("running");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                   e.printStackTrace();
                }
            }
        };
        log.debug("t1 state: {}", t1.getState()); // NEW
        t1.start();
        log.debug("t1 state: {}", t1.getState()); // RUNNABLE

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("t1 state: {}", t1.getState()); // TIMED_WAITING
    }
}
  1. 其它线程可以使用 interrupt 方法中断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException 异常
@Slf4j(topic = "c.d3_sleep_yield")
public class d3_sleep_yield {
    public static void main(String[] args) {
        Thread t1 = new Thread("t1"){
            @Override
            public void run() {
                log.debug("enter sleep");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    log.debug("wake up ...");
                   e.printStackTrace();
                }
            }
        };
        t1.start();

        try {
            Thread.sleep(1000); // 当前 main 线程睡眠1s
            log.debug("interrupt...");
            t1.interrupt(); // 打断 t1 的 sleep

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 输出:
         * 14:45:29 [t1] c.d3_sleep_yield - enter sleep
         * 14:45:30 [main] c.d3_sleep_yield - interrupt...
         * 14:45:30 [t1] c.d3_sleep_yield - wake up ...
         * java.lang.InterruptedException: sleep interrupted
         */
    }
}
  1. 睡眠结束后的线程未必会立刻得到执行。睡眠结束后的线程仅仅是被唤醒了,还需要等待CPU分配时间片才能执行

  2. TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性

iimport java.util.concurrent.TimeUnit;
// 该方法实际上是封装的 Thread.sleep 方法
TimeUnit.SECONDS.sleep(1); // 睡眠 1 s

yield

yield(让出):让出当前线程 CPU 的使用权给其他线程

  1. 调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程

  2. 具体的实现依赖于操作系统的任务调度器

线程优先级 set/getPriority

  • 线程优先级会提示(hint)调度器优先调度该线程,但它仅仅是一个提示,任务调度器可以忽略它
  • 如果 CPU 比较忙,那么优先级高的线程会获得更多的时间片,但 CPU闲时,优先级几乎没作用
public class d4_thread_priority {
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            int count = 0;
            while(true){
                System.out.println("---> 1 " + count++);
            }
        }, "t1");


        Thread t2 = new Thread(()->{
            int count = 0;
            while(true){
//                Thread.yield();
                System.out.println("         ---> 2 " + count++);
            }
        }, "t2");

        // 设置线程优先级(默认优先级为5)
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
    }
}
  • 设置 yield 会将当前线程占用的CPU时间片让给其他线程,所以 t1的 count 会比 t2 的大
  • 设置优先级,优先级越大的线程可以获得更多的时间片,所以 t2的 count 会比 t1 的大

防止 CPU 占用100%

xxx

join

等待当前线程运行完毕

单线程等待:主线程 main 在同步等待 t1 线程

@Slf4j(topic = "c.d5_join")
public class d5_join {
    static int r = 0;
    public static void main(String[] args) throws InterruptedException {
        test1();
    }
    private static void test1() throws InterruptedException {
        log.debug("开始");
        Thread t1 = new Thread(() -> {
            log.debug("开始");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.debug("结束");
            r = 10;
        });
        t1.start();
        t1.join(); // 等待 t1 完成,再获取 r的结果
        log.debug("结果为:{}", r);
        log.debug("结束");
    }
}

xx

多线程等待:

@Slf4j(topic = "c.d5_join")
public class d5_join {
    static int r1 = 0;
    static int r2 = 0;
    public static void main(String[] args) throws InterruptedException {
        test2();
    }
    private static void test2() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            r1 = 10;
        });
        Thread t2 = new Thread(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            r2 = 20;
        });
        long start = System.currentTimeMillis();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
        // 15:23:57 [main] c.d5_join - r1: 10 r2: 20 cost: 2014
    }

先调用 t1 的 join 再调用 t2 的join,等待时间为 2s

  • 第一个 join:等待 t1 时, t2 并没有停止, 而在运行
  • 第二个 join:1s 后, 执行到此, t2 也运行了 1s, 因此也只需再等待 1s

颠倒两个 join 最终都是输出 2s

  • 因为 t2等待运行完成的时候,t1 也在运行
  • t2 完成后已经等待了 2s,此时t1已经运行完毕,不需要再等待了

xx

有时效的 join

t1.join(1500); // 等待1.5后继续当前线程
// 如果 t1 仅需要 1s 完成,则join也会提前结束

interrupt

  1. 用于打断 sleep, wait, join的线程

打断后的打断标记为 false (认为对 sleep,wait,join的线程进行打断不算打断)

@Slf4j(topic = "c.d6_interrupt")
public class d6_interrupt {

    public static void main(String[] args) throws InterruptedException {
        test1();
    }
    private static void test1() throws InterruptedException {
        Thread t1 = new Thread(()->{
            log.debug("sleep...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        t1.start();
        Thread.sleep(500);
        log.debug("interrupt...");
        t1.interrupt();
        log.debug(" 打断状态: {}", t1.isInterrupted());
        /** 输出:
         * 15:36:35 [t1] c.d6_interrupt - sleep...
         * 15:36:36 [main] c.d6_interrupt - interrupt...
         * 15:36:36 [main] c.d6_interrupt -  打断状态: false
         */
    }
}
  1. 打断正常运行的线程

打断后的打断标记为 true。但是被打断的线程并不会停止运行

这样可以通过一个标记让该线程获取自己被其他线程打断了,以便进行后续处理并决定是否停止当前线程

@Slf4j(topic = "c.d6_interrupt")
public class d6_interrupt {

    public static void main(String[] args) throws InterruptedException {
        test2();
    }

    private static void test2() throws InterruptedException {
        Thread t2 = new Thread(()->{
            while(true) {
                // 获取当前线程的打断标记
                Thread current = Thread.currentThread();
                boolean interrupted = current.isInterrupted();
                // 自己决定是否退出当前线程
                if(interrupted) {
                    log.debug(" 打断状态: {}", interrupted);
                    // 15:39:55 [t2] c.d6_interrupt -  打断状态: true
                    break;
                }
            }
        }, "t2");
        t2.start();
        Thread.sleep(500);
        t2.interrupt();
    }
}

模式之两阶段终止

Two Phase Termination
在一个线程 T1 中如何“优雅”终止线程 T2?这里的【优雅】指的是给 T2 一个料理后事的机会。

  1. 错误方法
  • 使用线程对象的 stop() 方法停止线程
    • stop 方法会真正杀死线程,如果这时线程锁住了共享资源,那么当它被杀死后就再也没有机会释放锁,其它线程将永远无法获取锁
  • 使用 System.exit(int) 方法停止线程
    • 目的仅是停止一个线程,但这种做法会让整个程序都停止
  1. 两阶段终止模式

sss

利用 isInterrupted

注意事项:

sleep过程中被打断会重置打断标记为false,所以需要重新设置打断标记为 true,以便在上面的if里判断标记,进行后续处理

如果不重新设置打断标记为 true,则不会进行料理后事的处理

class Test{
    public static void main(String[] args) throws InterruptedException {
        d7_two_phase_termination tpt = new d7_two_phase_termination();
        tpt.start();

        Thread.sleep(3500);
        tpt.stop();
        /** 输出:
         * 16:07:57 [Thread-0] c.d7_two_phase_termination - 执行监控记录
         * 16:07:58 [Thread-0] c.d7_two_phase_termination - 执行监控记录
         * 16:07:59 [Thread-0] c.d7_two_phase_termination - 执行监控记录
         * java.lang.InterruptedException: sleep interrupted
         * 	at java.base/java.lang.Thread.sleep0(Native Method)
         * 	at java.base/java.lang.Thread.sleep(Thread.java:509)
         * 	at com.rainsun.d2_run_thread.d7_two_phase_termination.lambda$start$0(d7_two_phase_termination.java:30)
         * 	at java.base/java.lang.Thread.run(Thread.java:1583)
         * 16:08:00 [Thread-0] c.d7_two_phase_termination - 释放资源,锁,料理后事...
         */
    }
}

@Slf4j(topic = "c.d7_two_phase_termination")
public class d7_two_phase_termination {
    private Thread monitor;

    // 启动监控程序
    public void start(){
        monitor = new Thread(()->{
            while (true){
                Thread currentThread = Thread.currentThread();
                if(currentThread.isInterrupted()){
                    log.debug("释放资源,锁,料理后事...");
                    break;
                }

                try {
                    Thread.sleep(1000); // 情况一:sleep过程被打断
                    log.debug("执行监控记录"); // 情况二:执行其他过程被打断
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    // sleep过程中被打断会重置打断标记为false
                    // 这里需要重新设置打断标记为 true,以便在上面的if里判断标记,进行后续处理
                    currentThread.interrupt();
                }
            }
        });
        monitor.start();
    }

    public void stop(){
        monitor.interrupt();
    }
}

主线程与守护线程

  • 默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。

    • 例如:两个线程t1main ,main线程结束了, t1 线程没结束则Java进程会继续运行
  • 有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。

    • 设置一个线程为守护线程:t1.setDaemon(true)

t1 2s才运行完,但是 t1 被设置为守护线程,当其他线程 1s后运行完后,t1 线程也被迫停止了

@Slf4j(topic = "c.d8_daemon")
public class d8_daemon {
    public static void main(String[] args) throws InterruptedException {
        log.debug("开始运行...");
        Thread t1 = new Thread(() -> {
            log.debug("开始运行...");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            log.debug("运行结束...");
        }, "daemon");
        // 设置该线程为守护线程
        t1.setDaemon(true);
        t1.start();
        Thread.sleep(1000);
        log.debug("运行结束...");
        /**
         * 16:22:39 [main] c.d8_daemon - 开始运行...
         * 16:22:39 [daemon] c.d8_daemon - 开始运行...
         * 16:22:40 [main] c.d8_daemon - 运行结束...
         */
    }
}

注意

  • 垃圾回收器线程就是一种守护线程
  • Tomcat 中的 Acceptor 和 Poller 线程都是守护线程,所以 Tomcat 接收到 shutdown 命令后,不会等待它们处理完当前请求

操作系统层面的五种状态

在这里插入图片描述

  • 【初始状态】仅是在语言层面创建了线程对象,还未与操作系统线程关联
  • 【可运行状态】(就绪状态)指该线程已经被创建(与操作系统线程关联),可以由 CPU 调度执行
  • 【运行状态】指获取了 CPU 时间片运行中的状态当 CPU 时间片用完,会从【运行状态】转换至【可运行状态】,会导致线程的上下文切换
  • 【阻塞状态】
    • 如果调用了阻塞 API,如 BIO 读写文件,这时该线程实际不会用到 CPU,会导致线程上下文切换,进入【阻塞状态】
    • 等 BIO 操作完毕,会由操作系统唤醒阻塞的线程,转换至【可运行状态】
    • 与【可运行状态】的区别是,对【阻塞状态】的线程来说只要它们一直不唤醒,调度器就一直不会考虑调度它们
  • 【终止状态】表示线程已经执行完毕,生命周期已经结束,不会再转换为其它状态

Java API 层面的六种状态

aa

  • NEW 线程刚被创建,但是还没有调用 start() 方法
  • RUNNABLE 当调用了 start() 方法之后,注意,Java API 层面的 RUNNABLE 状态涵盖了 操作系统 层面的【可运行状态】、【运行状态】和【阻塞状态】(由于 BIO 导致的线程阻塞,在 Java 里无法区分,仍然认为是可运行)
  • BLOCKED , WAITING , TIMED_WAITING 都是 Java API 层面对【阻塞状态】的细分,后面会在状态转换一节详述
  • TERMINATED 当线程代码运行结束

六种状态的演示:

@Slf4j(topic = "c.d9_thread_state")
public class d9_thread_state {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            log.debug("running..."); // NEW
        }, "t1");


        Thread t2 = new Thread(()->{
            while (true){ // RUNNABLE

            }
        }, "t2");
        t2.start();

        Thread t3 = new Thread(()->{
            log.debug("running..."); // TERMINATED
        }, "t3");
        t3.start();

        Thread t4 = new Thread(()->{
            synchronized (d9_thread_state.class){
                try {
                    Thread.sleep(1000000); // timed_waiting
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }, "t4");
        t4.start();

        Thread t5 = new Thread(()->{
            try {
                t2.join(); // t5等待t2完成,t2为死循环,所以是 waiting状态
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t5");
        t5.start();

        Thread t6 = new Thread(()->{
            // 这个锁已经被t4占据了,所以t6拿不到这个锁。陷入 blocked状态
            synchronized (d9_thread_state.class){
                try {
                    Thread.sleep(1000000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }, "t6");
        t6.start();

        Thread.sleep(500);

        log.debug("t1 state {}", t1.getState());
        log.debug("t2 state {}", t2.getState());
        log.debug("t3 state {}", t3.getState());
        log.debug("t4 state {}", t4.getState());
        log.debug("t5 state {}", t5.getState());
        log.debug("t6 state {}", t6.getState());
        /** 输出:
         * 16:47:45 [t3] c.d9_thread_state - running...
         * 16:47:46 [main] c.d9_thread_state - t1 state NEW
         * 16:47:46 [main] c.d9_thread_state - t2 state RUNNABLE
         * 16:47:46 [main] c.d9_thread_state - t3 state TERMINATED
         * 16:47:46 [main] c.d9_thread_state - t4 state TIMED_WAITING
         * 16:47:46 [main] c.d9_thread_state - t5 state WAITING
         * 16:47:46 [main] c.d9_thread_state - t6 state BLOCKED
         */

    }
}
  • 23
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值