一、使用 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. 三十九、python面向对象一

    A.python面向对象 1.面向对象基础:面向对象三个特性:封装,继承,多态C# java 只能用面向对象编程Ruby,python 函数+面向对象 函数式编程:def 函数def f1(a): r ...

  2. web开发中会话跟踪的方法

    1. 什么是会话 会话是指一个终端用户(服务器)与交互系统(客户端)进行通讯的过程. 2. 什么是会话跟踪 对同一个用户对服务器的连续的请求和接受响应的监视.(将用户与同一用户发出的不同请求之间关联, ...

  3. Dataframe的索引问题

    1 两个Dataframe相加时,一定要注意索引是否对应再相加,利用这个特点有时可以先用set_index()将某些列置为索引列,再进行相加. import pandas as pd df1 = pd ...

  4. golang error (slice of unaddressable value)

    使用 Golang 将生成的 md5 转化为 string 的过程出现如下编译错误: 错误解析: 值得注意的一点是  func Sum(data []byte) [Size]byte  这个函数返回的 ...

  5. 查询oracle中所有用户信息 禁用用户

    ----查询oracle中所有用户信息 ----1.查询数据库中的表空间名称 ----1)查询所有表空间 select tablespace_name from dba_tablespaces; se ...

  6. robot framework python3环境下学习笔记(1)——安装robot framework

    安装环境:win10 64位,python3.6 1,安装robot framework pip install robotframework 2,安装wxPython pip install wxP ...

  7. [Mac Terminal] ___MAC终端清屏快捷键

    清全屏: command + K 清上一行命令:command +  L

  8. netcat命令用法

    1,端口扫描nc -z -v -n 172.31.100.7 21-25 2,聊天Server:nc -l 1567Client:nc 172.31.100.7 1567 3,文件传输Server:n ...

  9. 记:第一次更新服务器CUDA和GPU驱动

    因有需求需要改动centos7中的CUDA(更新到10)和GUP 的driver(更新到410)的版本. 事先需要查看原版本的信息,使用nvidia-smi可以查看driver的版本信息(最新的也显示 ...

  10. 使用ntpdate 同步 linux的时间

    1. linux 查看时间和时区的命令 timedatectl 效果为: Local time: Sun -- :: CST Universal time: Sun -- :: UTC RTC tim ...