Thread

Thread


概述

  • 继承 Runnable 接口,实现 run() 方法
  • Runnable 接口仅包含一个抽象的方法 run
  • Thread 继承 Runnable 接口,模板设计模式,主要的算法逻辑在模板类中完成,在继承类中进行具体的接口内容的设计
  • join 方法实现是通过 wait 方法

    /**
     * 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;
  • 线程最小优先级别:1
  • 线程默认优先级别:5
  • 线程最大优先级别:10
    /**
     * Returns a reference to the currently executing thread object.
     *
     * @return  the currently executing thread.
     */
    public static native Thread currentThread();
  • 当前正在执行的线程对象的引用

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()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        // threadStatus = 0 ,线程创建状态
        // 若同一个线程对象,已经执行过 start 方法,再次执行此 start 方法会抛出此异常
        if (threadStatus != 0) 
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this); // 添加进线程组

        boolean started = false;
        try {
            start0(); // 调用 native 方法启动新的线程,由 JVM 执行 run 方法
            started = true;
        } finally {
            try {
                if (!started) {
                    // 线程启动失败,将线程从线程组中移除
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();
  • 启动线程,直接让线程进入就绪状态,同时与主线程分开执行,主线程会继续执行后面的方法,而线程则会等待CPU资源,获取CPU资源之后开始运行RUN方法内的内容,RUN方法中包含了线程的需要执行的所有内容,执行完毕,线程结束
  • start方法只是设置了状态,并且调用了start0这个native方法,这个方法这里并没有具体实现也没有调用RUN方法去执行,原因是start0是个native方法,是由VM虚拟机本身的机制实现的(JVM的实现大部分是跟OS相关的,所以OS不同的话可能实现的机制有差异)
  • start0 方法运行起来了,调用Run执行方法体(具体的业务)
  • start0() 通过调用平台的API创建一个线程
  • Thread thread = new Thread() ; thread.start() ; 重复调用 thread 对象的 start 方法会抛出 IllegalThreadStateException
  • 原因:

join


    /**
     * Waits at most {@code millis} milliseconds for this thread to
     * die. A timeout of {@code 0} means to wait forever.
     *
     * <p> This implementation uses a loop of {@code this.wait} calls
     * conditioned on {@code this.isAlive}. As a thread terminates the
     * {@code this.notifyAll} method is invoked. It is recommended that
     * applications not use {@code wait}, {@code notify}, or
     * {@code notifyAll} on {@code Thread} instances.
     *
     * @param  millis
     *         the time to wait in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    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;
            }
        }
    }
  • join 方法是通过 wait 实现;且线程需要启动,如果仅仅是创建了线程,调用不会有效果
  • join 方法的作用:

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值