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;
}
}