一、使用 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. JS - defer 和 async

    普通 <script src="script.js"></script> 没有 defer 或 async,浏览器会立即加载并执行指定的脚本,"立 ...

  2. 歌手详情数据处理和Song类的封装

    我们现在每首歌曲的数据都是这样的 我们需要在这个数据里面去提取我们需要的部分,来构造成我们需要的数据对象 那我们要和创建singer.js一样  同样也要创建song.js类 我们还要获取到每首歌对应 ...

  3. Python Module_Socket_网络编程

    目录 目录 Socket 套接字 套接字的原理 套接字的数据处理方式 套接字类型 Socket 标准函数 ServerSocket 标准函数 ClientSocket 标准函数 公有标准函数 Sock ...

  4. 2017-0ctf-babyheap

    fastbin attack + unsortedbin attack + __malloc_hook 的基础利用 题目下载 : https://uaf.io/assets/0ctfbabyheap ...

  5. Go语言入门篇-命令 与 语法

    一.命令基础 1. go run : 用于运行命令源码文件(如:go run helloworld.go) 只能接受一个命令源码文件以及若干个库源码文件作为文件参数 其内部操作步骤: (1)先编译源码 ...

  6. mysql数据库负载均衡高可用之主从、主主备份,实时同步

    一:MySQL Replication 什么是MySQL Replication Replication可以实现将数据从一台数据库服务器(master)复制到一或多台数据库服务器(slave) 默认情 ...

  7. Docker 容器(container)及资源限制

    Container: 既然container是由image运行起来的,那么是否可以理解为container和image有某种关系?先来看张图: 其实可以理解为container只是基于image之后的 ...

  8. tarjan算法应用 割点 桥 双连通分量

    tarjan算法的应用. 还需多练习--.遇上题目还是容易傻住 对于tarjan算法中使用到的Dfn和Low数组. low[u]:=min(low[u],dfn[v])--(u,v)为后向边,v不是u ...

  9. PY个树状数组

    树状数组看起来比较简单,于是就挑它下手了... 于是生活终于也对咱下手了... 要讲的就两个东西,一个是开数组,全局变量写最前面,数组是这么开的: f=[0 for i in range(500005 ...

  10. MySQL 的自增 ID 用完了,怎么办?

      一.简述 在 MySQL 中用很多类型的自增 ID,每个自增 ID 都设置了初始值.一般情况下初始值都是从 0 开始,然后按照一定的步长增加.在 MySQL 中只要定义了这个数的字节长度,那么就会 ...