java Thread源码分析
一、使用 java 多线程
java多线程其中两种使用方式:
1、继承 Thread 类
2、实现 Runnable 接口
public class ThreadTest {
public static void main(String[] args) {
Thread t1 = new MyThread("thread-0001");
t1.start();
MyRunnable mr = new MyRunnable();
Thread t2 = new Thread(mr, "thread-0002");
t2.start();
}
private static class MyThread extends Thread{
public MyThread(String name) {
this.setName(name);
}
@Override
public void run() {
System.out.println(this.getName()+" thread run....");
}
}
private static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" runable run....");
}
}
}
二、线程初始化
继承 Thread 和 实现 Runnable 的方式都要经过初始化Thread构造函数的方式设置相关参数的过程。
构造函数如下:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(String name) {
init(null, null, name, 0);
}
public Thread(ThreadGroup group, String name) {
init(group, null, name, 0);
}
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
public Thread(ThreadGroup group, Runnable target, String name) {
init(group, target, name, 0);
}
public Thread(ThreadGroup group, Runnable target, String name, long stackSize) {
init(group, target, name, stackSize);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
} // 线程名
this.name = name; // 创建该线程时的线程(即父线程)
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
// 线程组
if (g == null) {
/* Determine if it's an applet or not */ /* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
} /* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
// 没有设置线程组时,默认线程组为父线程的线程组
if (g == null) {
g = parent.getThreadGroup();
}
} /* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess(); /*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
} g.addUnstarted(); // 设置线程组
this.group = g;
// 设置
this.daemon = parent.isDaemon();
// 设置优先级和父线程的优先级相同
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
// Runnable target
this.target = target;
setPriority(priority);
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize; /* Set thread ID */
// 设置线程的ID(threadSeqNumber),同步递增,每个线程都会生成一个thread ID
// 另外一个同步递增的ID (threadInitNumber),这个在没有显式指定线程名的时候,默认生成线程名(Thread-N)。
// 所以,threadSeqNumber >= threadInitNumber
tid = nextThreadID();
}
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
// 将线程添加到线程组中
group.add(this);
boolean started = false;
try {
// navite修饰的方法
start0();
started = true;
} finally {
try {
if (!started) {
// 线程启动失败,从线程组中移除线程
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
java Thread源码分析的更多相关文章
- java Thread源码分析(二)
一.sleep的使用 public class ThreadTest { public static void main(String[] args) throws InterruptedExcept ...
- Java Reference 源码分析
@(Java)[Reference] Java Reference 源码分析 Reference对象封装了其它对象的引用,可以和普通的对象一样操作,在一定的限制条件下,支持和垃圾收集器的交互.即可以使 ...
- Java 集合源码分析(一)HashMap
目录 Java 集合源码分析(一)HashMap 1. 概要 2. JDK 7 的 HashMap 3. JDK 1.8 的 HashMap 4. Hashtable 5. JDK 1.7 的 Con ...
- java集合源码分析(三):ArrayList
概述 在前文:java集合源码分析(二):List与AbstractList 和 java集合源码分析(一):Collection 与 AbstractCollection 中,我们大致了解了从 Co ...
- java集合源码分析(六):HashMap
概述 HashMap 是 Map 接口下一个线程不安全的,基于哈希表的实现类.由于他解决哈希冲突的方式是分离链表法,也就是拉链法,因此他的数据结构是数组+链表,在 JDK8 以后,当哈希冲突严重时,H ...
- Handler、Looper、MessageQueue、Thread源码分析
关于这几个之间的关系以及源码分析的文章应该挺多的了,不过既然学习了,还是觉得整理下,印象更深刻点,嗯,如果有错误的地方欢迎反馈. 转载请注明出处:http://www.cnblogs.com/John ...
- Java集合源码分析(三)Vevtor和Stack
前言 前面写了一篇关于的是LinkedList的除了它的数据结构稍微有一点复杂之外,其他的都很好理解的.这一篇讲的可能大家在开发中很少去用到.但是有的时候也可能是会用到的! 注意在学习这一篇之前,需要 ...
- Thread源码分析-java8
1.Thread特性分析 守护线程Daemon 定性:支持性线程,主要用于程序中后台调度以及支持性工作. 当JVM中不存在Daemon线程时,JVM将会退出. 将一个线程设定为Daemon的方法: 调 ...
- Java ArrayList源码分析(有助于理解数据结构)
arraylist源码分析 1.数组介绍 数组是数据结构中很基本的结构,很多编程语言都内置数组,类似于数据结构中的线性表 在java中当创建数组时会在内存中划分出一块连续的内存,然后当有数据进入的时候 ...
随机推荐
- shell脚本之浮点数和整数计算
整数计算 直接使用放括号计算即可,省去*号需要使用转义符的麻烦 #!/bin/bash num1= num2= var1=$[ $num1 * $num2 ] echo "$var1&quo ...
- Hook CreateProcess
6种比较常用的运行(执行)程序的方法: 包括WinExec.ShellExecute.CreateProcess.CreateProcessAsUser.CreateProcessWithLogonW ...
- leetcode 374. 猜数字大小(python)
我们正在玩一个猜数字游戏. 游戏规则如下:我从 1 到 n 选择一个数字. 你需要猜我选择了哪个数字.每次你猜错了,我会告诉你这个数字是大了还是小了.你调用一个预先定义好的接口 guess(int n ...
- iOS客户端使用教程
使用须知 支持 ios9.0 以上系统,兼容 iphone.ipad.ipod 等设备. 电脑上用 PP 助手安装 Shadowrocket Mac电脑上用PP助手安装Shadowrocket 下 ...
- Scratch少儿编程系列:(三)第一个例子 潜水员
一. 选择背景 在上一节系统界面的介绍中,选择"6角色"的左边,点击"从背景库中选择背景". 选择主题水下中的"underwater3". ...
- Snow的追寻--线段树维护树的直径
Snow终于得知母亲是谁,他现在要出发寻找母亲.王国中的路由于某种特殊原因,成为了一棵有n个节点的根节点为1的树,但由于"Birds are everywhere.",他得到了种种 ...
- js 中 json.stringfy()将对象、数组转换成字符串
json.stringfy()将对象.数组转换成字符串 var student = new Object(); student.name = "Lanny"; student.ag ...
- Codeforces 1262F Wrong Answer on test 233(组合数)
E1:设dp[i][j],表示在第i个位置的当前新状态超过原状态j分的方案数是dp[i][j],那么对于这种情况直接进行转移即可,如果a[i]==b[i]显然k种选择都可以,不影响j,如果不一样,这个 ...
- W3C标准下的盒模型与IE盒模型
标准盒模型如下图所示: IE下盒模型如下图所示:
- django中配置MySql
1.配置字段 在setting文件中配置数据库字段:数据库需要提前手动创建好:语句(create database testdb charset "utf8";) DATABASE ...