JAVA多线程详解(一)

1.线程状态

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;
    }

同一时刻只有一种状态,通过线程的getState()方法可以获取线程的状态,默认threadStatus是0。

private volatile int threadStatus = 0;

public static State toThreadState(int var0) {
        if ((var0 & 4) != 0) {
            return State.RUNNABLE;
        } else if ((var0 & 1024) != 0) {
            return State.BLOCKED;
        } else if ((var0 & 16) != 0) {
            return State.WAITING;
        } else if ((var0 & 32) != 0) {
            return State.TIMED_WAITING;
        } else if ((var0 & 2) != 0) {
            return State.TERMINATED;
        } else {
            return (var0 & 1) == 0 ? State.NEW : State.RUNNABLE;
        }
    }

2.状态转换

在这里插入图片描述

3.核心API简介

①start方法与run方法区别

public synchronized void start() {
        if (threadStatus != 0)   //判断线程状态,不是NEW,直接抛出异常,意味着线程不能重复执行
            throw new IllegalThreadStateException(); 
        group.add(this);   //往线程组中添加该线程
        boolean started = false;  //判断线程是否已经执行,默认为false
        try {
            start0();   native方法,C语言写的,会经过一系列处理,创建新线程,该新建线程调用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 */
            }
        }
    }

start0(); native方法,C语言写的,会经过一系列处理,创建新线程,该新建线程调用run方法

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

thread类调用此方法进而调用,自己重写的run方法中间未经过start方法底层c语言的一系列处理,仅作为普通方法处理,不会创建新线程

Java代码论证:

public class TestThread extends Thread {

    TestThread(String name){
        super(name);
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":请叫我大帅比!");
    }

    public static void main(String[] args)  {
        TestThread testThread = new TestThread("大帅比线程");
        testThread.run();
        testThread.start();
    }
}
main:请叫我大帅比!
大帅比线程:请叫我大帅比!

①如果run也会新建线程,线程会抛异常
②mian线程默认名字为main,可以看出run方法未新建线程,相当于main线程里面一个简单方法。
③Thread.currentThread().getName() 获取当前线程名称,不可改为this.getName(), 此处this均指TestThread类实例testThread。

②sleep方法概述

public static native void sleep(long millis) throws InterruptedException;  //毫秒级的sleep
public static void sleep(long millis, int nanos)   // “精确”到纳秒级别的sleep
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");  //negative  负数
        }
        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }
        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;   // 当纳秒数大于500000  或 纳秒不为0且毫秒为0时  直接毫秒数加1 ,不够精确!!!!
        }
        sleep(millis);
    }

底层还是native方法,作用是使当前线程休眠,位于同步代码块或同步方法内不会释放获得的锁。

一般的用TimeUnit.SECONDS.sleep(秒数);较优雅

sleep(0)的作用:可以释放cpu时间,让线程马上重新回到就绪队列而非等待队列,sleep(0)释放当前线程所剩余的时间片(如果有剩余的话),这样可以让操作系统切换其他线程来执行,提升效率。

③yield的作用

public static native void yield();

向调度程序提示当前线程愿意让出当前cpu分配的时间片。调度程序可以随意忽略此*提示。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值