Thread
构造
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");
}
//线程名,默认"Thread-" + nextThreadNum()
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;
//设置是否为守护线程,继承调用线程的主线程,main默认是false
this.daemon = parent.isDaemon();
//默认5
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 (inheritThreadLocals && parent.inheritableThreadLocals != null)
//创建线程共享变量副本
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
//设置栈大小,如果未指定大小,将在jvm 初始化参数中声明:Xss参数进行指定*/
this.stackSize = stackSize;
/* Set thread ID */
//设置线程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 */
}
}
}
interrupt
public void interrupt() {
//如果不是当前线程
if (this != Thread.currentThread())
//判断当前线程是否允许修改其他线程
checkAccess();
//中断
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
//设置中断标识位
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
join
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
//等待该线程终止的时间最长为 millis 毫秒。
if (millis == 0) {
//测试线程是否处于活动状态。如果线程已经启动且尚未终止,则为活动状态。
while (isAlive()) {
wait(0);
}
} else {
//指定了超时时间
while (isAlive()) {
long delay = millis - now;
//超时,结束
if (delay <= 0) {
break;
}
//等待阻塞
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
State
/* NEW:初始状态,线程被构建,还未调用start()方法;
RUNNABLE:运行状态,在java多线程模型中,就绪和运行都是运行状态;
BLOCKED:阻塞状态;
WAITING:等待状态,比如中断,需要其他的线程来唤醒;
TIME_WAITING:超时等待,可以在指定的时间内自行返回;
TERMINATED:终止状态,线程执行完毕。*/
public enum State {}
run
public void run() {
if (target != null) {
target.run();
}
}
总结
thread很多方法算是底层调用的了,
设置优先级调用,取决于操作系统
ThreadFactory
基本上都是当做内部类使用,随便看一个实现即可
java.util.concurrent.Executors.DefaultThreadFactory
DefaultThreadFactory
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
//默认继承父类线程组
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
//pool-自增1开始-thread-
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
//pool-1-thread-1
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
//是否是守护线程
if (t.isDaemon())
//如果是守护线程,则设置成普通线程
t.setDaemon(false);
//
//设置优先级,默认5
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}