Loading

java多线程笔记

  1. 多线程join 理解:java源码(1.8)
    public final synchronized void join(long millis)
        throws InterruptedException {
            long base = System.currentTimeMillis();
            long now = 0;
    
            if (millis < 0) {
                throw new IllegalArgumentException("timeout value is negative");
            }
    
            if (millis == 0) {
                while (isAlive()) {
                    wait(0);
                }
            } else {
                while (isAlive()) {
                    long delay = millis - now;
                    if (delay <= 0) {
                        break;
                    }
                    wait(delay);
                    now = System.currentTimeMillis() - base;
                }
            }
        }

    主要是

    synchronized 块中调用wait()方法来实现线程阻塞,达到先后的功能

    这里的疑惑两点:T1(主线程) T2(将要join到T1的线程
    a)wait() 一开始认为是阻塞调用join方法的线程,但这是不对的,这里的wait是调用的T1(主线程),而不是在T2的run()方法内的wait(),so...,
    b)既然有wait那应该有notify或者notifyall才会让T1主线程继续执行哈,但源码中没有,后得知,是当调用join方法后,在线程退出的时候会去调用ensure_join来确定当前线程时候join到其他线程,然后在调用notify_all(),源码在thread.cpp。

  2. interrupt给当前线程添加中断标识,在线程内部可调用Thread.currentThread().isInterrupted()来判断当前线程是否被中断。
    当线程内部有sleep方法时要注意,当线程处于sleep时,被interrupt后会触发sleep的InterruptedException异常,但此时interrupt还未执行
    完成,也就是说Thread.currentThread().isInterrupted()为false,导致线程没有中断,所以要在sleep()的catch块中添加
    Thread.currentThread().interrupt();来从新打断该线程。
  3. 线程的基本概念:创建、就绪、运行、阻塞和死亡。
    • NEW:线程刚被创建,没有调用该对象的start()方法之前,这时线程处于创建状态。
    • RUNNABLE:线程处于可执行状态,当调用了线程对象的start方法之后,
    • RUNNING:运行状态,执行run()方法中的程序。
    • BLOCKED、WAITING:线程被阻塞,线程执行过程中缺少某些条件而暂时阻塞,一旦它们等待的条件满足时,它们将回到 RUNNABLE 状态重新竞争 CPU。
    • TERMINATED:线程执行结束,被终止

  4. 线程与进程的区别:
posted @ 2019-07-07 13:58  ichar  阅读(208)  评论(0编辑  收藏  举报