多线程学习(二)- Thread源码分析

线程的状态
在这里插入图片描述
上图中各流程解释:
1: New 表示线程的创建,在没有实际调用start之前线程都是New的状态,此时 Thread 对象和其它 Java 对象没有什么不同,仅仅是存在于内存之中。
2:当我们调用start方法,子线程被创建之后,线程将进入Runnable状态。Thread 对象还在等待 CPU 的调用中。
3:子线程完成、被终止、被打断都会从Runnable状态转为terminated状态的转换。
4:如果子线程正在等待获取monitor lock锁时,如子线程正在等待获取进入synchronized 修饰的代码块时,线程将会处于阻塞状态,将从Runnable转Blocked。
5:WAITING 和 TIMED_WAITING 类似,都表示在遇到 Object#wait、Thread#join、LockSupport#park 这些方法时,线程就会等待另一个线程执行完特定的动作之后,才能结束等待,只不过 TIMED_WAITING 是带有等待时间的
Thread关系图
在这里插入图片描述
Thread实现Runnable接口,Runnable是一个函数式接口。具体代码如下:

package java.lang;

@FunctionalInterface
public interface Runnable {
 
    public abstract void run();
}

线程的优先级
在源码中priority表示了线程执行的优先级,priority值越高则线程将会优先被执行,反之。priority返回的结果为int类型范围为1-10,默认值为5,详解代码如下:

private int            priority;

/**
     * The minimum priority that a thread can have.
     */
    public final static int MIN_PRIORITY = 1;

   /**
     * The default priority that is assigned to a thread.
     */
    public final static int NORM_PRIORITY = 5;

    /**
     * The maximum priority that a thread can have.
     */
    public final static int MAX_PRIORITY = 10;

守护线程
线程默认不是守护线程的,若有需要则将daemon 设置为true,并且优先级很低,并jvm在退出时,不关心是否还有守护线程的存在。所以在日常开发中我们可以把一下和实际业务无关的但是有必要的代码以守护线程的方式去实现,即使jvm退出了这部分功能还可以实现,就算抛了异常也不影响业务代码。
线程初始化四种方法
1、继承 Thread 类
2、实现 Runnable 接口
3、使用 FutureTask
4、使用 Executor 框架
其中 1和2没有返回值

1: 继承Thread类,称为Thread的子类:

public class ThreadSimple extends Thread {

    private int count = 1000;

    @Override
    public void run() {
        count--;
        System.out.println(count);
        System.out.println(Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        ThreadSimple thread = new ThreadSimple();
        thread.start();
    }
}

2 实现Runnable,将实现Runnable子类做为Thread的参数.

public class RunnableSimple implements Runnable {
    private int count = 100;
    public void run() {
        count--;
        System.out.println(Thread.currentThread().getName());
        System.out.println(count);
    }

    public static void main(String[] args) {
        Thread thread = new Thread(new RunnableSimple());
        thread.start();
    }
}

不管是继承Thread还是实现Runnable接口他们都通过start或run的方式启动,可以根据实际的业务场景选择考虑使用start或run。
通过run是以主线程main去执行,而start则是开启一个子线程执行,
run方法:

 /* What will be run. */
    private Runnable target;
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

这里的target是指Runnable。而start方法则为:

public synchronized void start() {
        /**
        * threadStatus 默认为0
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
    }
 private native void start0();

start主要逻辑为:
1、检查线程的状态,是否可以启动;
2、把线程加入到线程group中;
3、调用了start0()方法。
从start 源码中我们可以发现start并不是执行run方法而是去执行了strat0方法,又发现start是一个native修饰的本地方法。在结合start方法的注解:

/**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */

及从Thread无参构造中Thread()

// 无参构造器,线程名字自动生成
public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}
// g 代表线程组,线程组可以对组内的线程进行批量的操作,比如批量的打断 interrupt
// target 是我们要运行的对象
// name 我们可以自己传,如果不传默认是 "Thread-" + nextThreadNum(),nextThreadNum 方法返回的是自增的数字
// stackSize 可以设置堆栈的大小
private void init(ThreadGroup g, Runnable target, String name,
                  long stackSize, AccessControlContext acc) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name.toCharArray();
    // 当前线程作为父线程
    Thread parent = currentThread();
    this.group = g;
    // 子线程会继承父线程的守护属性
    this.daemon = parent.isDaemon();
    // 子线程继承父线程的优先级属性
    this.priority = parent.getPriority();
    // classLoader
    if (security == null || isCCLOverridden(parent.getClass()))
        this.contextClassLoader = parent.getContextClassLoader();
    else
        this.contextClassLoader = parent.contextClassLoader;
    this.inheritedAccessControlContext =
            acc != null ? acc : AccessController.getContext();
    this.target = target;
    setPriority(priority);
    // 当父线程的 inheritableThreadLocals 的属性值不为空时
    // 会把 inheritableThreadLocals 里面的值全部传递给子线程
    if (parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals =
            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    this.stackSize = stackSize;
    /* Set thread ID */
    // 线程 id 自增
    tid = nextThreadID();
}

从初始化源码中可以看到,很多属性,子线程都是直接继承父线程的,包括优先性、守护线程、inheritableThreadLocals 里面的值等等。

在run方法中可知target为Runnable,且它为Thread的成员变量。
所以可以得出如下:
在这里插入图片描述
其他方法
1、Thread.sleep(sleepNum);表示线程休眠多久,当前逻辑执行到此不再继续执行,而是等待指定的时间。但在这段时间内,该线程持有的 monitor 锁并不会被放弃,一直占用资源不会释放在此期间。sleep有两个重载方法如下

public static native void sleep(long millis) throws InterruptedException;
public static void sleep(long millis, int nanos)
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

两者的区别只是一个支持休眠时间到毫秒级,另外一个到纳秒级。但其实第二个并不能真的精确到纳秒级别,当nanos大于五万后则会四舍五入,直接进行millis++.

2、 Thread.yield();当前线程做出让步,放弃当前 cpu,让 cpu 重新选择线程,避免线程过度使用 cpu,我们在写 while 死循环的时候,预计短时间内 while 死循环可以结束的话,可以在循环里面使用 yield 方法,防止 cpu 一直被 while 死循环霸占.

3、interrupt();interrupt 中文是打断的意思,意思是可以打断中止正在运行的线程,比如:
Object.wait ()、Thread.join ()、Thread.sleep (long) 这些方法运行后,线程的状态是 WAITING 或 TIMED_WAITING,这时候打断这些线程,就会抛出 InterruptedException 异常,使线程的状态直接到 TERMINATED;
如果 I/O 操作被阻塞了,我们主动打断当前线程,连接会被关闭,并抛出 ClosedByInterruptException 异常;调用 interrupt 方法,并不会影响可中断方法之外的逻辑。线程不会中断,会继续执行。这里的中断概念并不是指中断线程;
一旦调用了 interrupt 方法,那么线程的 interrupted 状态会一直为 ture(没有通过调用可中断方法或者其他方式主动清除标识的情况下);
如:

public class ThreadSimple extends Thread {

    private int count = 1000;

    @Override
    public void run() {
        try {
            Thread.sleep(3000);
            count--;
            System.out.println(count);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            System.out.println("线程被打断");
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSimple thread = new ThreadSimple();
        thread.start();
        Thread.sleep(100);
        thread.interrupt();
    }
}

主线程会等待0.1秒,如果子线程还没有执行完成的,则直接打断
在这里插入图片描述
4、join 的意思就是当前线程等待另一个线程执行完成之后,才能继续操作如的demo:

public class ThreadSimple extends Thread {

    public int count = 1000;

    @Override
    public void run() {
        try {
            Thread.sleep(4000);
            count -= 100;
            System.out.println("子线程进行减一百" + count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread main = Thread.currentThread();
        ThreadSimple thread = new ThreadSimple();
        System.out.println(main.getName() + thread.getCount());
        thread.start();
        thread.join();
        System.out.println(thread.getName());
        System.out.println(main.getName() + thread.getCount());
    }

5、wait
原本 RUNNING 的线程,可以通过调用 wait 方法,进入 BLOCKING 状态。此线程会放弃原来持有的锁。
6 、notify
调用 notify 方法则会唤醒 wait 的线程,让其继续往下执行(如果获得锁了以后)。
7、notify与notifyAll 区别:
当有线程调用了对象的 notifyAll()方法会唤醒所有 wait 线程。
而 notify()方法只会随机唤醒一个 wait 线程,被唤醒的的线程便会进入该对象的锁池中,锁池中的线程会去竞争该对象锁。也就是说,调用了notify后只要一个线程会由等待池进入锁池,而notifyAll会将该对象等待池内的所有线程移动到锁池中,等待锁竞争
优先级高的线程竞争与获得对象锁成正比,假若某线程没有竞争到该对象锁,它还会留在锁池中,唯有线程再次调用 wait()方法,它才会重新回到等待池中。而竞争到对象锁的线程则继续往下执行,直到执行完了 同步代码块,它会释放掉该对象锁,这时锁池中的线程会继续竞争该对象锁。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值