多线程(三)——了解线程

本文详细介绍了Java线程的六种状态及其转换,包括新建、就绪、阻塞、等待、睡眠和终止状态。同时,解析了start(), run(), yield(), join()等关键方法的实现原理和使用场景,帮助理解线程的管理和协作。
摘要由CSDN通过智能技术生成

一、状态

线程共有6个状态。

状态名称
new(新建状态)用new创建的线程处于新建状态,此时他和其他的Java对象一样,仅仅在堆中分配了内存,没有调用start方法。
runable(就绪状态)调用start方法,线程处于就绪状态
blocked(阻塞状态)因为某些原因放弃CPU(缺少资源:IO、锁),暂时停止运行,进入阻塞状态
waiting(等待状态)线程中的对象的调用wait()时,JVM就会将线程放入到等待池中
timed_waiting(睡眠状态)在指定的等待时间内等待线程的状态
terminated(终止状态)线程已经执行完毕

源码如下:

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }
  1. 正常的线程只有四个状态:新建状态(NEW)、RUNNABLE(就绪状态)、终止状态(TERMINATED)。
  2. 非正常状态:阻塞状态(BLOCKED)、等待状态(WAITING)、睡眠状态(TIME WAITING)

二、方法

2.1 start()

启动操作系统的线程,进入就绪队列,等待CPU分配时间片,获取到时间片后执行线程的run方法。(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".
         */
        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();
            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 */
            }
        }
    }

2.2 run()

业务逻辑的实现方法。

  1. 直接调用run方法不会启动线程
  2. 调用start方法以后,JVM会自动的运行run方法

源码如下:

/**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

2.3 yield()

将运行中的线程便会就绪状态,让出cpu的执行权,并通知操作系统从就绪线程中选出线程运行(可选择原来执行yield的线程)

注意:不释放资源

源码如下:

/**
     * A hint to the scheduler that the current thread is willing to yield
     * its current use of a processor. The scheduler is free to ignore this
     * hint.
     *
     * <p> Yield is a heuristic attempt to improve relative progression
     * between threads that would otherwise over-utilise a CPU. Its use
     * should be combined with detailed profiling and benchmarking to
     * ensure that it actually has the desired effect.
     *
     * <p> It is rarely appropriate to use this method. It may be useful
     * for debugging or testing purposes, where it may help to reproduce
     * bugs due to race conditions. It may also be useful when designing
     * concurrency control constructs such as the ones in the
     * {@link java.util.concurrent.locks} package.
     */
    public static native void yield();

2.4 join()

当有新的线程加入时,主线程会进入等待(waiting)状态,一直到调用join()方法的线程执行结束为止。

当不调用join方法时,等到主线程执行完,才执行其他线程。

Runnable runnable = new RunnableDemo(){
    @Override
    public void run() {
        System.out.println("执行中....");
    }
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
System.out.println("执行完毕");

执行结果:

执行完毕
执行中....
执行中....

调用join方法时,先执行指定线程

Runnable runnable = new RunnableDemo(){
  @Override
    public void run() {
        System.out.println("执行中....");
    }
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();

try{
    t1.join();
    t2.join();
}catch (Exception e){
    e.printStackTrace();
}
System.out.println("执行完毕");

执行结果:

执行中....
执行中....
执行完毕

三、状态与方法关系图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值