Thread

  • 属性说明
/**
* 程序中的执行线程
* @since 1.0
*/
public
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
} /**
* 线程名称
*/
private volatile String name; /**
* 线程优先级
*/
private int priority; /**
* 此线程是否是守护线程
*/
private boolean daemon = false; /**
* 将运行的目标
*/
private Runnable target; /**
* 此线程所在的线程组
*/
private ThreadGroup group; /**
* 当前线程的上下文类加载器
*/
private ClassLoader contextClassLoader; /**
* 此线程继承的访问控制上下文
*/
private AccessControlContext inheritedAccessControlContext; /**
* 匿名线程的自增编号
*/
private static int threadInitNumber; /** 与当前线程绑定的 ThreadLocalMap */
ThreadLocal.ThreadLocalMap threadLocals = null; /**
* 继承的 ThreadLocalMap
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; /**
* 此线程请求的堆栈大小,如果未设置则由 JVM 自己决定
*/
private long stackSize; /**
* 此线程的 ID
*/
private long tid; /**
* 线程名称序列 ID
*/
private static long threadSeqNumber; /**
* 此线程的状态
*/
private volatile int threadStatus; /**
* 当前线程在此目标对象 parkBlocker 上阻塞
* java.util.concurrent.locks.LockSupport.park.
*/
volatile Object parkBlocker; /**
* 阻塞此线程的可中断 IO 对象
*/
private volatile Interruptible blocker; /**
* 阻塞锁
*/
private final Object blockerLock = new Object(); /**
* 线程的最小优先级
*/
public static final int MIN_PRIORITY = 1; /**
* 线程的默认优先级
*/
public static final int NORM_PRIORITY = 5; /**
* 线程的最大优先级
*/
public static final int MAX_PRIORITY = 10;
  • 常用静态方法
    /**
* 当前线程所在线程组中估计的活跃线程数
*/
public static int activeCount() {
return currentThread().getThreadGroup().activeCount();
} /**
* 返回当前执行线程
*/
@HotSpotIntrinsicCandidate
public static native Thread currentThread(); /**
* 打印当前线程的堆栈信息,只用于调试
*/
public static void dumpStack() {
new Exception("Stack trace").printStackTrace();
} /**
* 当前线程是否持有目标对象的监视器
* @since 1.4
*/
public static native boolean holdsLock(Object obj); /**
* 返回并清空当前线程的中断状态
*
* @revised 6.0
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
} /**
* 让当前线程自旋等待一会
* @since 9
*/
@HotSpotIntrinsicCandidate
public static void onSpinWait() {} /**
* 当前线程休眠指定的毫秒数
*
* @param millis 休眠的毫秒数
*/
public static native void sleep(long millis) throws InterruptedException; /**
* 当前线程愿意让步处理器时间,从运行状态进入就绪状态
*/
public static native void yield();
  • 实例化
    /**
* 创建运行目标任务 target 的新线程
*
* @param target 目标 Runnable 任务
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
} /**
* 创建运行目标任务 target 的新线程,并指定线程名称,方便排查问题
*
* @param target 目标 Runable 任务
* @param name 新线程的名称
*/
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
  • 常用方法
    /**
* 此线程是否还存活
*/
public final native boolean isAlive(); /**
* 此线程是否是守护线程
*/
public final boolean isDaemon() {
return daemon;
} /**
* 此线程是否已经被设置中断标识,同时清除其中断标识。
*
* @revised 6.0
*/
public boolean isInterrupted() {
return isInterrupted(false);
} /**
* 返回线程创建时自动生成的ID
*/
public long getId() {
return tid;
} /**
* 读取此线程的名称
*/
public final String getName() {
return name;
} /**
* 读取此线程的优先级
*/
public final int getPriority() {
return priority;
} /**
* 返回此线程的状态
* @since 1.5
*/
public State getState() {
// get current thread state
return jdk.internal.misc.VM.toThreadState(threadStatus);
} /**
* 线程状态
*/
public enum State {
/**
* 线程刚创建,还未启动
*/
NEW, /**
* 线程正在运行
*/
RUNNABLE, /**
* 此线程在等待获取指定对象的监视器,已经阻塞
*/
BLOCKED, /**
* 此线程在阻塞等待其他线程的信号
*/
WAITING, /**
* 此线程在超时阻塞等待
*/
TIMED_WAITING, /**
* 此线程已经终止
*/
TERMINATED;
} /**
* 读取此线程的调用堆栈
* @since 1.5
*/
public StackTraceElement[] getStackTrace() {
if (this != Thread.currentThread()) {
// check for getStackTrace permission
final SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.GET_STACK_TRACE_PERMISSION);
}
// 线程已经死亡,则返回空的调用堆栈
if (!isAlive()) {
return EMPTY_STACK_TRACE;
}
final StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
StackTraceElement[] stackTrace = stackTraceArray[0];
// a thread that was alive during the previous isAlive call may have
// since terminated, therefore not having a stacktrace.
if (stackTrace == null) {
stackTrace = EMPTY_STACK_TRACE;
}
return stackTrace;
} else {
return new Exception().getStackTrace();
}
} /**
* 启动当前线程
*/
public synchronized void start() {
/**
* 线程不是新建状态
*/
if (threadStatus != 0) {
throw new IllegalThreadStateException();
} // 将此线程加入线程组
group.add(this); boolean started = false;
try {
// 启动线程
start0();
started = true;
} finally {
try {
// 如果启动失败,则将其从线程组中移除
if (!started) {
group.threadStartFailed(this);
}
} catch (final Throwable ignore) {
}
}
} private native void start0(); /**
* 中断当前线程
*/
public void interrupt() {
if (this != Thread.currentThread()) {
checkAccess();
} synchronized (blockerLock) {
final Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
// 中断此线程
interrupt0();
} /**
* 阻塞等待当前线程执行完毕
*/
public final void join() throws InterruptedException {
join(0);
} /**
* 在指定的毫秒内阻塞等待此线程执行完毕
*
* @param millis 阻塞等待的毫秒数
*/
public final synchronized void join(long millis)
throws InterruptedException {
// 当前毫秒数
final long base = System.currentTimeMillis();
long now = 0;
// 毫秒数非法
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
// 毫秒数为 0,则表示无限期阻塞等待此线程执行完毕
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
// 线程处于存活状态
while (isAlive()) {
// 计算延时
final long delay = millis - now;
if (delay <= 0) {
break;
}
// 阻塞等待
wait(delay);
// 重新计算时间
now = System.currentTimeMillis() - base;
}
}
} /**
* 在当前线程中执行目标任务
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}

Thread 源码阅读的更多相关文章

  1. 【原】SDWebImage源码阅读(四)

    [原]SDWebImage源码阅读(四) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 SDWebImage中主要实现了NSURLConnectionDataDelega ...

  2. 【原】SDWebImage源码阅读(三)

    [原]SDWebImage源码阅读(三) 本文转载请注明出处 —— polobymulberry-博客园 1.SDWebImageDownloader中的downloadImageWithURL 我们 ...

  3. 源码阅读系列:EventBus

    title: 源码阅读系列:EventBus date: 2016-12-22 16:16:47 tags: 源码阅读 --- EventBus 是人们在日常开发中经常会用到的开源库,即使是不直接用的 ...

  4. EventBus源码解析 源码阅读记录

    EventBus源码阅读记录 repo地址: greenrobot/EventBus EventBus的构造 双重加锁的单例. static volatile EventBus defaultInst ...

  5. 20 BasicTaskScheduler0 基本任务调度类基类(二)——Live555源码阅读(一)任务调度相关类

    这是Live555源码阅读的第二部分,包括了任务调度相关的三个类.任务调度是Live555源码中很重要的部分. 本文由乌合之众 lym瞎编,欢迎转载 http://www.cnblogs.com/ol ...

  6. Bean实例化(Spring源码阅读)-我们到底能走多远系列(33)

    我们到底能走多远系列(33) 扯淡: 各位:    命运就算颠沛流离   命运就算曲折离奇   命运就算恐吓着你做人没趣味   别流泪 心酸 更不应舍弃   ... 主题: Spring源码阅读还在继 ...

  7. Netty源码阅读(一) ServerBootstrap启动

    Netty源码阅读(一) ServerBootstrap启动 转自我的Github Netty是由JBOSS提供的一个java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速 ...

  8. AQS源码阅读笔记(一)

    AQS源码阅读笔记 先看下这个类张非常重要的一个静态内部类Node.如下: static final class Node { //表示当前节点以共享模式等待锁 static final Node S ...

  9. Mina源码阅读笔记(四)—Mina的连接IoConnector2

    接着Mina源码阅读笔记(四)-Mina的连接IoConnector1,,我们继续: AbstractIoAcceptor: 001 package org.apache.mina.core.rewr ...

随机推荐

  1. Java反射【一、概述】

    .net也使用过反射,不过用的比较浅显,用来记日志等.. Java基础课程学习已经过了一段时间了,接下来继续学习 本次学习包含以下内容 Java反射[一.概述] Java反射[二.Class类的使用] ...

  2. JDBC及PreparedStatement防SQL注入

    概述 JDBC在我们学习J2EE的时候已经接触到了,但是仅是照搬步骤书写,其中的PreparedStatement防sql注入原理也是一知半解,然后就想回头查资料及敲测试代码探索一下.再有就是我们在项 ...

  3. apk 查看sha1签名

    1,首先使用解压工具解开apk. 2,进入meta-inf文件夹,进入命令行模式 输入如下命令 keytool -printcert -file CERT.RSA

  4. Centos 安装 kubectl kubelet kubeadm

    cat <<EOF > /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://m ...

  5. JMeter函数整理

    "_intSum” 功能:用于计算多个整数的和,可以是计算正整数和负整数的和,它有N个参数,最少有3个参数,最多不限.最后一个参数是函数名称,前面的其它参数是要求和的整数.这个函数在函数对话 ...

  6. Tourist's Notes CodeForces - 538C (贪心)

    A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist no ...

  7. unittest 详解

      内容总括 一. 初始化 setUp 与 tearDown setUpClass 与 tearDownClass unittest.main(verbosity=0/1/2) 二. 执行顺序 按顺序 ...

  8. Docker 运行ELK日志监测系统,汉化Kibana界面

    1.ELK日志监控简介 ELK由Elasticsearch.Logstash和Kibana三部分组件组成: Elasticsearch是个开源分布式搜索引擎,它的特点有:分布式,零配置,自动发现,索引 ...

  9. React组件(组件属性this.state和this.props,css样式修饰组件)

    目录: 1.创建组件的第一种方式 function2.将组件抽离为单独的jsx文件3.省略.jsx后缀, 配置webpack设置根目录4.创建组件的第二种方式--使用class关键字创建组件5.组件私 ...

  10. if语句分析

    1.if语句的反汇编判断 if语句反汇编后的标志:     执行各类影响标志位的指令             jxx xxxx 如果遇到上面的指令,则很可能是if语句:   例如:     1.案例一 ...