Java自学之路—线程的属性及常用API

143 阅读3分钟

「这是我参与2022首次更文挑战的第12天,活动详情查看:2022首次更文挑战

Hope is a good thing, maybe the best of things. And no good thing ever dies—— 《The Shawshank Redemption》

前言

Java 本身的概念还是比较多的,所以学习的开始还是要先打好基础,从一些基本的概念入手,这些都是Java的一些常识。在Java的面试中都是很重要的东西。

今天我们来学一下线程的属性及常用API。

线程的属性

ID

每一个线程的唯一标识,就是一个简单的数值,我们可以通过api getId()

/**
 * Returns the identifier of this Thread.  The thread ID is a positive
 * <tt>long</tt> number generated when this thread was created.
 * The thread ID is unique and remains unchanged during its lifetime.
 * When a thread is terminated, this thread ID may be reused.
 *
 * @return this thread's ID.
 * @since 1.5
 */
public long getId() {
    return tid;
}

name

表示线程的名称,不同的线程可以使用相同的名称

private volatile String name;

我们可以使用api getName()去获取线程名称;使用setName(String)设置线程名称。

  • getName()
/**
 * Returns this thread's name.
 *
 * @return  this thread's name.
 * @see     #setName(String)
 */
public final String getName() {
    return name;
}
  • setName(String)
/**
 * Changes the name of this thread to be equal to the argument
 * <code>name</code>.
 * <p>
 * First the <code>checkAccess</code> method of this thread is called
 * with no arguments. This may result in throwing a
 * <code>SecurityException</code>.
 *
 * @param      name   the new name for this thread.
 * @exception  SecurityException  if the current thread cannot modify this
 *               thread.
 * @see        #getName
 * @see        #checkAccess()
 */
public final synchronized void setName(String name) {
    checkAccess();
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;
    if (threadStatus != 0) {
        setNativeName(name);
    }
}

priority

线程的优先级,决定了线程的执行顺序,优先级高的先执行,执行完毕后再执行优先级低的。

在不同的操作系统中(java运行的环境),优先级还是有差别的,取决于系统自身的调度机制。

我们可以通过api getPriority()去获取;可以通过setPriority(int)去设置。

线程的优先级是用int类型表示,默认是5,在Java中有3个优先级的常量:源码如下

/**
  * 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;

daemon

守护线程就是为了其它线程服务的,被守护的线程被称为用户线程。守护线程依存于被守护的线程。当被守护的线程退出时,守护线程也就退出了无论它是否执行完毕。

我们可以用api setDaemon(boolean) 讲一个线程设置为守护线程。

如果要为主线程设置守护线程,必须是在主线程开始之前,否则是无效的。

package start;

public class DaemonThread {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
            }
        };

        Thread subThread = new Thread(runnable);
        subThread.setDaemon(true); // 设置为主线程的守护线程
        subThread.start();
        System.out.println("主线程准备推出了。。。");
    }
}

image.png

结语

如果这篇文章帮到了你,欢迎点赞👍和关注⭐️。

文章如有错误之处,希望在评论区指正🙏🙏

欢迎关注我的微信公众号,一起交流技术,微信搜索 🔍 :「 五十年以后