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. JavaJDBC【三、增删改查】

    获取数据库连接后,可进行增删改查操作 语句生成: Statement s = con.createStatement(sql); //生成语句 PreparedStatement ps = (Prep ...

  2. mtd介绍

    转:http://blog.csdn.net/lwj103862095/article/details/21545791 MTD,Memory Technology Device即内存技术设备 字符设 ...

  3. 十一,k8s集群访问控制之ServicAccount

    目录 认证安全 连接Api-Server的两类账号 ServiceAccount 创建 使用admin 的SA 测试 URL访问kubernetes资源 APIserver客户端定义的配置文件 kub ...

  4. 天线basic

    1.实际应用时,按内置天线还是外置天线考虑. 内置时,净空区在 PCB 上所有层(all layer) 不能放置元件,走线和铺 GND  天线远离金属,至少要距离周围有较高的元器件 10 毫米以上: ...

  5. CentOS下安装软件

    CentOS下安装软件,要看下载的软件安装包的后缀名是什么,一般为了方便安装,推荐下载以 rpm 结尾的软件包. 比如以下截图,有多种下载方式,推荐下载圈起来的链接. rpm包安装方式步骤: 找到相应 ...

  6. java线程基础巩固---Thread中断Interrupt方法学习&采用优雅的方式结束线程生命周期

    Interrupt学习: 在jdk中关于interrupt相关方法有三个,如下: 关于上面的疑问会在稍后进行阐述滴,下面看代码: 编译运行: 应该说是t线程为啥在被打断之后没有退出,还是在运行状态,这 ...

  7. Cookie/Session的机制

    Cookie的机制 Cookie是浏览器(User Agent)访问一些网站后,这些网站存放在客户端的一组数据,用于使网站等跟踪用户,实现用户自定义功能. Cookie的Domain和Path属性标识 ...

  8. 使用幕布时,在Session过期后,弹出框加载出登陆的HTML的问题

    思路:在登陆页面判断当前加载的Url是否时login/index ,如果不是跳转到登陆页 //设置或获取对象指定的文件名或路径. var Url = window.location.pathname; ...

  9. pyinstall python文件打包成二进制exe文件

    pycharm + python3 + win7 1 pip install pyinstall  (官网) 2 准备 .py 文件 3 具体例子 from PyQt5.QtWidgets impor ...

  10. 题解 比赛 match

    比赛 match Description 有 N 支队伍打比赛.已知有如下条件: • 每支队伍恰好打了 4 场比赛 • 对于一场比赛,如果是平局,双方各得 1 分:否则胜者得 3 分,负者不得分 给定 ...