线程的状态与sleep()、yield()、join()方法-多线程与高并发

目录

1、线程的状态:

2、sleep、yield、join


1、线程的状态:

Thread类中有一个内部枚举类State,枚举了6种线程的状态。

/**
     * A thread state.  A thread can be in one of the following states:
     * <ul>
     * <li>{@link #NEW}<br>
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>
     *
     * <p>
     * A thread can be in only one state at a given point in time.
     * These states are virtual machine states which do not reflect
     * any operating system thread states.
     *

特定时间点,线程的状态只可能是这6种状态中的一种。程序执行过程中,可以通过Thread.getState()方法获取当前线程的状态。具体介绍如下:

  • NEW:线程还未开始的的状态,即调用start方法前的状态。(Thread state for a thread which has not yet started.)
  • RUNNABLE :线程的可执行的就绪状态,此时线程正在等待操作系统为虚拟机的当前线程分配系统资源。(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.) 
  • BLOCKED:阻塞状态,为了执行进入一个同步方法或者在调用wait方法后再次进入同步方法,而等待锁。(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}.)
  • WAITING:等待状态,线程调用了wait()、join() 、park()方法(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 {@code Object.wait()}
              on an object is waiting for another thread to call
              {@code Object.notify()} or {@code Object.notifyAll()} on
              that object. A thread that has called {@code Thread.join()}
              is waiting for a specified thread to terminate.)
  • TIMED_WAITING:倒计时等待状态,线程调用了和倒计时相关的方法,比如sleep()(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>)
  •   TERMINATED:终止状态,线程执行完毕后处于该状态。( Thread state for a terminated thread. The thread has completed execution.)

 

2、sleep、yield、join

sleep当前线程暂停运行指定时间,将CPU让给其他线程继续执行,暂停运行完指定时间后当前线程回到就绪状态。

yield当前线程回到就绪等待队列,让出一下cpu,但并不保证让出之后,下个执行的线程不是当前的线程

join:当前线程t1调用其他线程t2的join方法,等t2的逻辑执行完后,t1在继续执行,类似于方法调用。join可以保证一个线程执行完毕后再执行另一个线程,保证执行顺序。

package main.java.basic;

public class Sleep_Yield_Join {
    public static void main(String[] args) {
//        testSleep();
//        testYield();
        testJoin();
    }

    static void testSleep() {
        new Thread(()->{
            for(int i=0; i<100; i++) {
                System.out.println("A" + i);
                try {
                    Thread.sleep(500);
                    //TimeUnit.Milliseconds.sleep(500)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static void testYield() {
        new Thread(()->{
            for(int i=0; i<100; i++) {
                System.out.println("A" + i);
                if(i%10 == 0) Thread.yield();


            }
        }).start();

        new Thread(()->{
            for(int i=0; i<100; i++) {
                System.out.println("------------B" + i);
                if(i%10 == 0) Thread.yield();
            }
        }).start();
    }

    static void testJoin() {
        Thread t1 = new Thread(()->{
            for(int i=0; i<100; i++) {
                System.out.println("t1:" + i);
                try {
                    Thread.sleep(500);
                    //TimeUnit.Milliseconds.sleep(500)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(()->{

            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for(int i=0; i<100; i++) {
                System.out.println("t2:" + i);
                try {
                    Thread.sleep(500);
                    //TimeUnit.Milliseconds.sleep(500)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值