并发编程原理与实战(二)Thread类关键API详解

并发编程原理与实战(一)精准理解线程的创建和停止

上一篇文章学习了线程的创建和停止的正确方法,本文我们来学习Thread类的构造函数、常见成员属性、主要方法,对Thread类进一步学习,因为Thread类的一些方法跟线程并发协同相关,学好这些方法有助于后面对并发协同的掌握。

我们已经知道Thread类有多个构造方法,以下源码基于jdk21。我们选取其中一个参数最长的带 AccessControlContext 参数的构造函数进行讲解,这个构造函数的入参包含了所有类型的入参,把这个构造函数搞懂了,其他的自然也就懂了。

/**
     * Initializes a platform Thread.
     *
     * @param g the Thread group, can be null
     * @param name the name of the new Thread
     * @param characteristics thread characteristics
     * @param task the object whose run() method gets called
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *        AccessController.getContext() if null
     */
    @SuppressWarnings("removal")
    Thread(ThreadGroup g, String name, int characteristics, Runnable task,
           long stackSize, AccessControlContext acc)

从注释中可以看出:

1、参数g可以将线程归属到某个线程组,方便对线程进行分组分类管理。

2、参数name可以指定线程的名称,方便对线程进行跟踪调试。

3、参数characteristics,早期的jdk版本中并没有包含该参数,字面意思是线程特征,用来指定线程是否可以继承当前线程(父线程)的本地变量。

4、参数task可以指定线程运行的任务。

5、参数stackSize可以指定线程栈的大小。我们知道,方法的调用过程涉及入栈出栈,线程栈大小决定了线程可以使用的栈内存量,这对于一些特殊的业务场景非常重要,比如方法调用层级过深(如递归),大量局部变量这些场景,通过指定线程栈的大小来提升系统性能。

6、参数acc指定线程的安全上下文,用于权限控制。在某些情况下,可能想要限制或控制线程对某些资源的访问,以确保线程操作的安全性。这时可以通过指定线程的安全上下文来实现。

下面通过一个例子来说明上述参数的使用。

public class ThreadTask1 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" run");
    }
    public static void main(String[] args) {
        for(int i=0;i<3;i++) {
            //创建线程组1
            ThreadGroup threadGroup = new ThreadGroup("group1");
            //创建线程指定线程组、线程任务、线程名称
            Thread t = new Thread(threadGroup, new ThreadTask1(), "group1-thread"+i);
            t.start();
        }

        for(int i=0;i<3;i++) {
            //创建线程组2
            ThreadGroup threadGroup2 = new ThreadGroup("group2");
            //创建线程指定线程组、线程任务、线程名称
            Thread t2 = new Thread(threadGroup2, new ThreadTask2(), "group2-thread"+i);
            t2.start();
        }

        //主线程中获取当前访问控制上下文
        AccessControlContext parentContext = AccessController.getContext();

        // 创建子线程并传入主线程的访问控制上下文
        new Thread(() -> {
            // 在子线程中使用主线程的访问控制上下文检查权限
            try {
                parentContext.checkPermission(new FilePermission("/tmp/test.txt", "read"));
                System.out.println("Permission pass");
            } catch (AccessControlException e) {
                System.out.println("Permission refuse: " + e.getMessage());
            }
        }).start();

    }
}

public class ThreadTask2 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" run");
    }
}

运行结果

group1-thread0 run
group1-thread1 run
group1-thread2 run
group2-thread1 run
group2-thread2 run
group2-thread0 run
Permission refuse: access denied ("java.io.FilePermission" "/tmp/test.txt" "read")

上面的例子中,在主线程中分别创建2组子线程并指定子线程的名称,然后在主线程中创建读取/tmp/test.txt文件的子线程,在子线程中使用主线程的访问控制上下文检查子线程是否有读取文件的权限,无权限则抛出异常。

Thread类的属性

我们摘取常见的属性进行分析。

...    
// thread id
private final long tid;

// thread name
private volatile String name;

// interrupt status (read/written by VM)
volatile boolean interrupted;
...
/*
 * ThreadLocal values pertaining to this thread. This map is maintained
 * by the ThreadLocal class.
 */
ThreadLocal.ThreadLocalMap threadLocals; 
...
/**
 * A thread state.  A thread can be in one of the following states:
 ...
 */
public enum State {
    NEW,//新建状态
    RUNNABLE,//可运行状态
    BLOCKED,//阻塞状态
    WAITING,//无限期等待状态
    TIMED_WAITING,//限期等待状态
    TERMINATED;//终止状态
}    

1、tid,线程唯一标识,由JVM分配,不同线程的ID不重复。从jdk19开始,已经废弃了用getId()获取线程唯一标识,改有用threadId()方法获取。

2、name,线程的名称,可以通过getName()方法获取。

3、interrupted,线程的中断状态,用来标识线程是否被中断。

4、threadLocals,线程本地变量,用来存储跟本线程有关的变量。

4、State,线程运行状态,一共6中状态,用枚举表示,通过getState()方法进行获取。

Thread类的常用方法

1、start()方法

/**
 * Schedules this thread to begin execution. The thread will execute
 * independently of the current thread.
 *
 * <p> A thread can be started at most once. In particular, a thread can not
 * be restarted after it has terminated.
 *
 * @throws IllegalThreadStateException if the thread was already started
 */
public void start() {
    synchronized (this) {
        // zero status corresponds to state "NEW".
        if (holder.threadStatus != 0)
            throw new IllegalThreadStateException();
        start0();
    }
}

前一篇文章中,我们已经接触过start()方法了。调用该方法后,线程将会被安排调度运行(注意:调用该方法线程不是马上运行,线程进入新建状态,所以是"被安排调度运行"),线程将会独立于当前线程运行。一个线程最多只能启动一次,并且不能在终止后重新启动。

2、run()方法

/**
 * This method is run by the thread when it executes. Subclasses of {@code
 * Thread} may override this method.
 *
 * <p> This method is not intended to be invoked directly. If this thread is a
 * platform thread created with a {@link Runnable} task then invoking this method
 * will invoke the task's {@code run} method. If this thread is a virtual thread
 * then invoking this method directly does nothing.
 *
 * @implSpec The default implementation executes the {@link Runnable} task that
 * the {@code Thread} was created with. If the thread was created without a task
 * then this method does nothing.
 */
@Override
public void run() {
    Runnable task = holder.task;
    if (task != null) {
        Object bindings = scopedValueBindings();
        runWith(bindings, task);
    }
}

Thread类实现了Runnable接口并重写了run()方法。当线程运行的时候该方法被运行,子类应该重写该方法。需要注意的是,该方法并不是用来直接调用的,如果这个线程是随着Runnable类型的任务创建的平台线程,调用此方法时,Runnable任务的run()方法将会被执行。如果此线程是虚拟线程,那么直接调用这个方法什么也不做。虚拟线程是jdk21的性特性,后面我们将会学到。

3、sleep()方法


/**
 * Causes the currently executing thread to sleep (temporarily cease
 * execution) for the specified number of milliseconds, subject to
 * the precision and accuracy of system timers and schedulers. The thread
 * does not lose ownership of any monitors.
 *
 * @param  millis
 *         the length of time to sleep 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 static void sleep(long millis) throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    long nanos = MILLISECONDS.toNanos(millis);
    ThreadSleepEvent event = beforeSleep(nanos);
    try {
        if (currentThread() instanceof VirtualThread vthread) {
            vthread.sleepNanos(nanos);
        } else {
            sleep0(nanos);
        }
    } finally {
        afterSleep(event);
    }
}

调用该方法使当前正在执行的线程进入休眠(暂时停止执行),睡眠时间为指定的毫秒数。需要注意的是,调用该方法线程不会失去拥有的监视器(或者称为锁资源)。

4、join()方法

/**
 * Waits for this thread to terminate.
 *
 * <p> An invocation of this method behaves in exactly the same
 * way as the invocation
 *
 * <blockquote>
 * {@linkplain #join(long) join}{@code (0)}
 * </blockquote>
 *
 * @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 void join() throws InterruptedException {
    join(0);
}

调用join()方法将会等待当前线程运行结束,如在main()方法中主线程调用t.join(),那么主线程将会等子线程t执行完成后继续执行,通常用在一些需要多线程并发协同的场景。

5、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 void yield() {
        if (currentThread() instanceof VirtualThread vthread) {
            vthread.tryYield();
        } else {
            yield0();
        }
    }

yield字面上有“让步、出让、放弃”的意思,所以调用该方法将向调度器发出当前线程可以让出CPU的提示。意在提高那些可能有过度使用CPU的程序性能。

6、wait()/wait(long timeoutMillis)/wait(long timeoutMillis, int nanos)方法

Object类是所有java类的父类,所以Thread类同样拥有Object类可以继承的方法,其中wait()/wait(long timeoutMillis)/wait(long timeoutMillis, int nanos)、notify()/notifyAll()这几个方法是跟控制线程执行状态有关的方法。

调用wait()/wait(long timeoutMillis)/wait(long timeoutMillis, int nanos)方法后,线程进入等待状态直到被其他线程调用notify()/notifyAll()方法唤醒,或者指定的睡眠时间已经用完。

7、notify()/notifyAll()方法

调用notify(),任意一个处于等待状态的线程将被唤醒;调用notifyAll()方法后,所有处于等待状态的线程将被唤醒。

8、interrupt()方法

上一篇文章中已经学习过该方法,主要用来优雅的终止处于阻塞或者等待状态的线程。在此不再详述。

9、interrupted()方法

/**
 * Tests whether the current thread has been interrupted.  The
 * <i>interrupted status</i> of the thread is cleared by this method.  In
 * other words, if this method were to be called twice in succession, the
 * second call would return false (unless the current thread were
 * interrupted again, after the first call had cleared its interrupted
 * status and before the second call had examined it).
 *
 * @return  {@code true} if the current thread has been interrupted;
 *          {@code false} otherwise.
 * @see #isInterrupted()
 * @revised 6.0, 14
 */
public static boolean interrupted() {
    return currentThread().getAndClearInterrupt();
}

该方法是一个静态方法。interrupted字面意思是被中断的,是interrupt的过去分词和过去式,所以该方法用来测试线程是否被中断过。

...
// interrupt status (read/written by VM)
volatile boolean interrupted;
...
boolean getAndClearInterrupt() {
    boolean oldValue = interrupted;
    // We may have been interrupted the moment after we read the field,
    // so only clear the field if we saw that it was set and will return
    // true; otherwise we could lose an interrupt.
    if (oldValue) {
        interrupted = false;
        clearInterruptEvent();
    }
    return oldValue;
}

从源码中可以看出,中断状态用一个属性名为"interrupted"布尔型的变量,表示是否被中断过,并由jvm进行读写操作。准确的讲,调用该方法后如果线程已经处于被中断的状态,线程的中断状态将被设置成false,但是返回的是被设置前的状态。

10、isInterrupted()方法

/**
 * Tests whether this thread has been interrupted.  The <i>interrupted
 * status</i> of the thread is unaffected by this method.
 *
 * @return  {@code true} if this thread has been interrupted;
 *          {@code false} otherwise.
 * @see     #interrupted()
 * @revised 6.0, 14
 */
public boolean isInterrupted() {
    return interrupted;
}

该方法是一个成员方法,仅仅是返回线程中断状态变量的值,测试线程是否已经被中断过。不用刻意去背interrupt()、interrupted()、isInterrupted()三者的区别,从单词的本意和官方注释去理解它们的区别。

‌11、其他方法

(1)currentThread()‌,这是一个静态方法,返回当前执行线程。

(2)threadId(),获取线程唯一标识,jdk19之前用getId()方法获取。

(3)getName(),获取当前线程的名称。

(4)setName(String name)‌,设置线程的名称。

(5)isAlive()‌,判断线程是否存活。

‌(6)isDaemon() ,判断当前线程是否是守护线程(后台线程),JVM 在所有非守护线程结束后自动退出。

(7)setDaemon(boolean on)‌,设置线程为守护线程。

(8)getState(),获取线程的运行状态。

总结

本文对Thread类的构造函数、主要成员变量、常用成员方法进行了讲解,目的是了解线程具有哪些行为操作,进一步加深对线程的理解。Thread类的常用方法还是比较多的,下面用一个表格总结这些方法。

类别核心方法应用场景
线程启动与执行控制start(), run()创建并执行线程
线程状态控制sleep(), join(),yield(), wait(), notify(), notifyAll()控制线程执行状态
线程属性设置与获取setName(), getName(), isDaemon(), isDaemon()配置线程名称、守护模式
线程中断与终止控制interrupt(), interrupted(), isInterrupted()优雅终止线程
线程信息与状态查询currentThread(), threadId(), getName(), setName(), isAlive(),isDaemon(), setDaemon() , getState()监控线程运行状态

如果文章对您有帮助,不妨“帧栈”一下,关注“帧栈”公众号,第一时间获取推送文章,您的肯定将是我写作的动力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帧栈

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值