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. 读书笔记《SpringBoot编程思想》

    目录 一. springboot总览 1.springboot特性 2.准备运行环境 二.理解独立的spring应用 1.应用类型 2.@RestController 3.官网创建springboot ...

  2. D-Link系列路由器漏洞挖掘入门

    D-Link系列路由器漏洞挖掘入门 前言 前几天去上海参加了geekpwn,看着大神们一个个破解成功各种硬件,我只能在下面喊 6666,特别羡慕那些大神们.所以回来就决定好好研究一下路由器,争取跟上大 ...

  3. 在values中添加colors.xml

    如何在values中添加colors.xml文件?按钮上的文字,背景色的动态变化的xml放在res/drawable里,现在我就说静态的xml文件吧. res/values/colors.xml< ...

  4. 使用HTML5 -Canvas追踪用户,Chrome隐身模式阵亡

    中国的一些精准营销公司又要偷着乐了= =从之前追踪Cookie到后面追踪FlashCookie,某些商家总在永无止境的追踪用户行为甚至是隐私,将其转化为所谓的“商业价值”.我们被迫面临“世风日下.道德 ...

  5. vue.js 简介

    Vue.js是什么 Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的 渐进式框架.与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计.Vue 的核心库只关注视图层 ...

  6. QT对话框

    QFileDialog:文件对话框 QString fileName=QFileDialog::getOpenFileName(this,"打开文件", "/" ...

  7. css全部理解

    如何设置标签样式 给标签设置长宽 只有块儿级标签才可以设置长宽 行内标签设置了没有任何作用(仅仅只取决于内部文本值) 字体颜色 color后面可以跟多种颜色数据 颜色英文 red #06a0de 直接 ...

  8. nginx静态资源服务

    静态文件 动态文件 需要算法,函数封装后,返回给浏览器端的 静态资源的服务场景----CDN 异步I/O-----效果不明显 tcp_nopush  注意,须在sendfile开启的前提下 技术思想: ...

  9. Parallels Desktop虚拟机无法关机提示“虚拟机处理器已被操作系统重置”

    如果你在使用PD的时候遇到了这样子的弹窗,恭喜你篇博文可以帮助你,因为我刚刚也遇到了这个问题.如果有帮助可以点一下推荐按钮. 针对Windows电脑 启动虚拟机 创建快照 使用管理员权限运行命令提示符 ...

  10. 【Python之路】特别篇--Python面向对象(进阶篇)

    上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...