一、使用 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. 浏览器端-W3School:HTML DOM cells 集合

    ylbtech-浏览器端-W3School:HTML DOM cells 集合 1.返回顶部 1. HTML DOM cells 集合 HTML DOM Table 对象 定义和用法 cells 集合 ...

  2. 阶段3 1.Mybatis_12.Mybatis注解开发_6 mybatis注解开发一对一的查询配置

    新建Account实体类 生成getter和setter还有toString方法 先创建dao类 全局的配置,这里要改成package 创建多对一的关系 在查询的时候输出user这个对象的内容 建立查 ...

  3. 系统分析与设计HW4

    个人作业 用例建模 a. 阅读 Asg_RH 文档,绘制用例图. b. 选择你熟悉的定旅馆在线服务系统(或移动 APP),如绘制用例图.并满足以下要求: 对比 Asg_RH 用例图,请用色彩标注出创新 ...

  4. IIS Express 使用方法

    配置文件位置: "%userprofile%\My Documents\IISExpress\config\applicationhost.config" 站点配置节: <s ...

  5. Android专项测试监控资源

    版本号 V 1.1.0 Android性能测试分为两类:1.一类为rom版本(系统)的性能测试2.一类为应用app的性能测试(本次主要关注点为app的性能测试) Android的app性能测试包括的测 ...

  6. python 爬虫入门1 爬取代理服务器网址

    刚学,只会一点正则,还只能爬1页..以后还会加入测试 #coding:utf-8 import urllib import urllib2 import re #抓取代理服务器地址 Key = 1 u ...

  7. 【MM系列】SAP 关于物料间的替代问题

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP 关于物料间的替代问题   前 ...

  8. 【MM系列】SAP 通过原材料找到成品的函数

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[MM系列]SAP 通过原材料找到成品的函数   ...

  9. Java多线程学习——synchronized锁机制

    Java在多线程中使用同步锁机制时,一定要注意锁对对象,下面的例子就是没锁对对象(每个线程使用一个被锁住的对象时,得先看该对象的被锁住部分是否有人在使用) 例子:两个人操作同一个银行账户,丈夫在ATM ...

  10. .net core 学习小结之环境配置篇

    安装IIs对 netcore 的支持 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-mod ...