一、使用 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);
}
  上述构造函数涉及的参数:
  ThreadGroup group(该线程所属线程组)、Runnable targer、String name(线程名)、long stackSize(线程堆栈大小,不知道有什么作用,日后再填坑)。
  最终会执行 init 函数:
 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();
}
  t1.start()会调用本地方法start0()启动线程:
 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源码分析的更多相关文章

  1. java Thread源码分析(二)

    一.sleep的使用 public class ThreadTest { public static void main(String[] args) throws InterruptedExcept ...

  2. Java Reference 源码分析

    @(Java)[Reference] Java Reference 源码分析 Reference对象封装了其它对象的引用,可以和普通的对象一样操作,在一定的限制条件下,支持和垃圾收集器的交互.即可以使 ...

  3. Java 集合源码分析(一)HashMap

    目录 Java 集合源码分析(一)HashMap 1. 概要 2. JDK 7 的 HashMap 3. JDK 1.8 的 HashMap 4. Hashtable 5. JDK 1.7 的 Con ...

  4. java集合源码分析(三):ArrayList

    概述 在前文:java集合源码分析(二):List与AbstractList 和 java集合源码分析(一):Collection 与 AbstractCollection 中,我们大致了解了从 Co ...

  5. java集合源码分析(六):HashMap

    概述 HashMap 是 Map 接口下一个线程不安全的,基于哈希表的实现类.由于他解决哈希冲突的方式是分离链表法,也就是拉链法,因此他的数据结构是数组+链表,在 JDK8 以后,当哈希冲突严重时,H ...

  6. Handler、Looper、MessageQueue、Thread源码分析

    关于这几个之间的关系以及源码分析的文章应该挺多的了,不过既然学习了,还是觉得整理下,印象更深刻点,嗯,如果有错误的地方欢迎反馈. 转载请注明出处:http://www.cnblogs.com/John ...

  7. Java集合源码分析(三)Vevtor和Stack

    前言 前面写了一篇关于的是LinkedList的除了它的数据结构稍微有一点复杂之外,其他的都很好理解的.这一篇讲的可能大家在开发中很少去用到.但是有的时候也可能是会用到的! 注意在学习这一篇之前,需要 ...

  8. Thread源码分析-java8

    1.Thread特性分析 守护线程Daemon 定性:支持性线程,主要用于程序中后台调度以及支持性工作. 当JVM中不存在Daemon线程时,JVM将会退出. 将一个线程设定为Daemon的方法: 调 ...

  9. Java ArrayList源码分析(有助于理解数据结构)

    arraylist源码分析 1.数组介绍 数组是数据结构中很基本的结构,很多编程语言都内置数组,类似于数据结构中的线性表 在java中当创建数组时会在内存中划分出一块连续的内存,然后当有数据进入的时候 ...

随机推荐

  1. 复选框checked 选中后不显示打钩

    复选框checked 选中后不显示打钩 checkbox属性checked="checked"已有,但复选框却不显示打钩的原因   复选框绑定了click事件,点一次选中,再点击取 ...

  2. MySQL表碎片清理

    MySQL大表清理 生产环境data库业务表base_data大小:500G,data_free:31G mysql> SELECT table_schema,table_name,data_f ...

  3. TiDB官方文档

    TiDB官方文档: https://github.com/pingcap/docs-cn TiDB 整体架构 TiDB 集群主要包括三个核心组件:TiDB Server,PD Server 和 TiK ...

  4. 构造Map并对其排序

    #构造Map并对其排序 attr_tul = ['a','b','c','d','e','f'] one_tul = [,,,,,] one_dic = {} for i in range(len(a ...

  5. deepfm代码参考

    https://github.com/lambdaji/tf_repos/blob/master/deep_ctr/Model_pipeline/DeepFM.py https://www.cnblo ...

  6. Unity3D 可空值类型 Nullable

    值类型的变量永远不会变null,因为值类型是其本身不会变成null.引用类型可变成null,内存会全部使用0来表示null,因为这种开销会降低,仅仅需要将一块内存清除. 表示一些空值的方案: 1.使用 ...

  7. 如何在linux上部署vue项目

    安装nginx的前奏 安装依赖 yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel 创建一个文件夹 cd /usr/ ...

  8. 【Python】我的第一个完整的小说爬虫

    写在开头 纪念我的第一个爬虫程序,一共写了三个白天,其中有两个上午没有看,中途遇到了各种奇怪的问题,伴随着他们的解决,对于一些基本的操作也弄清楚了.果然,对于这些东西的最号的学习方式,就是在使用中学习 ...

  9. 应用安全 - 工具 | 数据库 - redis - 漏洞 - 汇总

    未授权访问 Date 类型 未授权访问导致getshell 影响范围 复现 (1)shell反弹 (2)结合SSH服务 (3)结合web服务 分析

  10. DG on Windows 10 S: 执行任意代码

    DG on Windows 10 S: 执行任意代码 windows 10 S版本是什么鬼? 众所周知,我们使用的是windows 10企业版 LTSC.更准确一点,CMD运行winver,我的版本是 ...