Java中Thread源码剖析(二)

2014-11-24 00:07:49 · 作者: · 浏览: 1
(t == null) {
return;
}


synchronized (t) {
while (isAlive()) {
t.wait();
}
}
}

8、join堵塞当前线程,使其处于等待状态,因为子线程执行的时间可能比主线程执行时间还长,所以join是主线程需要在它执行完后再销毁。当然也可以加参数join(long millis, int nanos),使其等待N秒N毫秒,如果它已经处于join方法,则报InterruptedException 。

public final void setDaemon(boolean isDaemon) {
if (hasBeenStarted) {
throw new IllegalThreadStateException(Thread already started.); // TODO Externalize
}


if (vmThread == null) {
daemon = isDaemon;
}
}

9、设置为守护线程,必须的runnable执行前设置,会在其他已经没有非守护线程运行的时候执行。

public final void setPriority(int priority) {
if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
throw new IllegalArgumentException(Priority out of range); // TODO Externalize
}


if (priority > group.getMaxPriority()) {
priority = group.getMaxPriority();
}


this.priority = priority;


VMThread vmt = this.vmThread;
if (vmt != null) {
vmt.setPriority(priority);
}
}

10、优先级主要通过VMThread来设置的,注意最高设为10最低为1,否则报 IllegalArgumentException。

public static void sleep(long millis, int nanos) throws InterruptedException {

        VMThread.sleep(millis, nanos);
}

11、执行sleep,如果在sleep期间被interrupt,会报InterruptedException。

/**
* Starts the new Thread of execution. The run() method of
* the receiver will be called by the receiver Thread itself (and not the
* Thread calling start()).
*
* @throws IllegalThreadStateException if the Thread has been started before
*
* @see Thread#run
*/
public synchronized void start() {
if (hasBeenStarted) {
throw new IllegalThreadStateException(Thread already started.); // TODO Externalize
}


hasBeenStarted = true;


VMThread.create(this, stackSize);
}

12、线程开始执行,如果start已经执行,则报IllegalThreadStateException

@Deprecated
public final synchronized void stop(Throwable throwable) {
throw new UnsupportedOperationException();
}

13、stop方法弃用

public static void yield() {
VMThread.yield();
}

14、给另一个准备运行的线程让路,让它先执行

关于join和yield的区别,更在上一节:

Java中join和yield的作用