■ 临界资源与临界区
一般指的是公共共享资源,即可以被多个线程共享使用。但同一时间只能由一个线程去访问和操作临界区的资源,一旦临界区资源被一个线程
占用,其他线程也想要使用该资源就必须等待,
就好比好多人想上大号,但只有一个坑,一个人占了坑,其他人就得排队等待喽
临界区可以认为是一段代码,线程会在该端代码中访问共享资源,因此临界区的界定标准就是是否访问共享(临界)资源(有点类似形成闭包的概
念);一次只允许有一个程序(进程/线程)在该临界区中
■ 类定义
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does.
初始化时调用 Java 本地方法,实现了Runnable接口
*/
private static native void registerNatives();
static {
registerNatives();
}
■ 构造器
/**
* 默认构造器
* 其中name规则为 "Thread-" + nextThreadNum()
*/
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
/**
* 创建一个指定Runnable的线程
* 其中name规则为 "Thread-" + nextThreadNum()
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
/**
* 创建一个指定所属线程组和Runnable的线程
* 其中name规则为 "Thread-" + nextThreadNum()
*/
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}
/**
* 创建一个指定name线程
*/
public Thread(String name) {
init(null, null, name, 0);
}
/**
* 创建一个指定所属线程组和name的线程
*/
public Thread(ThreadGroup group, String name) {
init(group, null, name, 0);
}
/**
* 创建一个指定Runnable和name的线程
*/
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
/**
* Allocates a new {@code Thread} object so that it has {@code target}
* as its run object, has the specified {@code name} as its name,
* and belongs to the thread group referred to by {@code group}.
* 创建一个新的Thread对象,同时满足以下条件:
* 1.该线程拥有一个指定的Runnable对象用于方法执行
* 2.该线程具有一个指定的名称
* 3.该线程属于一个指定的线程组ThreadGroup
* <p>If there is a security manager, its
* {@link SecurityManager#checkAccess(ThreadGroup) checkAccess}
* method is invoked with the ThreadGroup as its argument.
* 若这里有个安全管理器,则ThreadGroup将调用checkAccess方法进而触发SecurityManager的checkAccess方法
* <p>In addition, its {@code checkPermission} method is invoked with
* the {@code RuntimePermission("enableContextClassLoaderOverride")}
* permission when invoked directly or indirectly by the constructor of a subclass which
* overrides the {@code getContextClassLoader} or {@code setContextClassLoader} methods.
* 当enableContextClassLoaderOverride被开启时,checkPermission将被重写子类直接或间接地调用
* <p>The priority of the newly created thread is set equal to the
* priority of the thread creating it, that is, the currently running
* thread. The method {@linkplain #setPriority setPriority} may be
* used to change the priority to a new value.
* 新创建的Thread的优先级等同于创建它的线程的优先级,调用setPriority会变更其优先级
* <p>The newly created thread is initially marked as being a daemon
* thread if and only if the thread creating it is currently marked
* as a daemon thread. The method {@linkplain #setDaemon setDaemon}
* may be used to change whether or not a thread is a daemon.
* 当且仅当线程创建时被显示地标记为守护线程,新创建的线程才会被初始化为一个守护线程
* setDaemon方法可以设置当前线程是否为守护线程
*/