码迷,mamicode.com
首页 > 编程语言 > 详细

多线程基础-基础实现

时间:2020-12-18 12:21:01      阅读:2      评论:0      收藏:0      [点我收藏+]

标签:invoke   并发   shared   组织   sse   orm   star   ==   object   

一:线程与进程的概念

进程(Process) 是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。 在当代面向线程设计的计算机结构中,进程是线程的容器。程序是指令、数据及其组织形式的描述,进程是程序的实体

线程(thread) 是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

总结:

进程:指在系统中正在运行的一个应用程序;程序一旦运行就是进程;进程——资源分配的最小单位。

线程:系统分配处理器时间资源的基本单元,或者说进程之内独立执行的一个单元执行流。线程——程序执行的最小单位。

二:使用进程的两种方法以及源码解析

1.集成Thread类

public class ThreadEx extends Thread{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}

启动代码:
ThreadEx extendThread = new ThreadEx();
extendThread.start();

2.实现Runnable接口

class ThreadIm implements Runnable {
private int currentIndex = 0;
@Override
public void run() {
     currentIndex += 1
System.out.println(Thread.currentThread().getName() + ":" + ++currentIndex);
}
}
ThreadIm implementsThread = new ThreadIm();
Thread thread1 = new Thread(implementsThread);
Thread thread2 = new Thread(implementsThread);
thread1.start();
thread2.start();
结果:
Thread-2:2
Thread-1:2

这里有一个很有意思的问题:  就是同样一个线程实例 被执行多次 那么 他的属性 就是非线程安全的了

3.Thread源码

属性:

native表示是由着C++封装的底层方法

private static native void registerNatives(); 
static {
registerNatives();
}

private volatile char name[];
private int priority;
/* Whether or not the thread is a daemon thread. */
private boolean daemon = false; //是否是守护线程
/* What will be run. 执行的线程*/
private Runnable target;
/* The group of this thread 线程组别*/
private ThreadGroup group;
/* The context ClassLoader for this thread 加载器*/
private ClassLoader contextClassLoader;
/* For autonumbering anonymous threads. */
private static int threadInitNumber; //线程初始化数字 每次执行都会+1 用以初始化名字以及标记
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;

/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class. 是否是可继承的ThreadLocal
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

/* Thread ID :tidy = ++threadSeqNumber */
 private long tid;

/* For generating thread ID */
private static long threadSeqNumber;

/* Java thread status for tools,
* initialized to indicate thread ‘not yet started‘
*/

private volatile int threadStatus = 0;


private static synchronized long nextThreadID() {
return ++threadSeqNumber;
}

/**
* The argument supplied to the current call to
* java.util.concurrent.locks.LockSupport.park.
* Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
* Accessed using java.util.concurrent.locks.LockSupport.getBlocker
*/
volatile Object parkBlocker;

/* The object in which this thread is blocked in an interruptible I/O
* operation, if any. The blocker‘s interrupt method should be invoked
* after setting this thread‘s interrupt status.
*/
private volatile Interruptible blocker;
private final Object blockerLock = new Object();

/* Set the blocker field; invoked via sun.misc.SharedSecrets from java.nio code
*/
void blockedOn(Interruptible b) {
synchronized (blockerLock) {
blocker = b;
}
}

public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;

构造方法:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
Thread(Runnable target, AccessControlContext acc) {
init(null, target, "Thread-" + nextThreadNum(), 0, acc);
}
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(String name) {
init(null, null, name, 0);
}
等等,大致上来说在构造的时候一定会调用初始化方法 然后给线程中的某些属性赋值
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name.toCharArray(); //名字初始化
Thread parent = currentThread(); //得到当前线程的父线程
SecurityManager security = System.getSecurityManager(); //安全管理器是一个允许应用程序实现安全策略的类
if (g == null) { //组别为空 则使用父亲的组别
if (security != null) {
g = security.getThreadGroup();
}
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();
this.target = target;
setPriority(priority);
if (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 */
tid = nextThreadID();
}
start启动犯法
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 {
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 */
}
}
}



 

多线程基础-基础实现

标签:invoke   并发   shared   组织   sse   orm   star   ==   object   

原文地址:https://www.cnblogs.com/nooker/p/14127392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!