1. 构造线程
运行线程前需要构造线程对象,这一步在Thread类的初始化部分(以下为init方法的源码):
代码语言:javascript复制 /**
* Initializes a Thread.
*
* @param g the Thread group
* @param target the object whose run() method gets called
* @param name the name of the new Thread
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
* @param acc the AccessControlContext to inherit, or
* AccessController.getContext() if null
* @param inheritThreadLocals if {@code true}, inherit initial values for
* inheritable thread-locals from the constructing 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");
}
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();
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 */
tid = nextThreadID();
}
可以看到,初始化线程的时候需要提供一些属性:所属线程组,线程优先级,是否Daemon等。且都是根据其parent线程进行空间分配的。
2. 启动线程
线程初始化之后,调用start()方法就能启动这个线程。
3. 中断
- 中断可以视作线程的一个标识位属性,标识一个运行中的线程是否被其他线程进行了中断操作。
- 其他线程可以通过调用该线程的interrupt()方法对其进行中断操作
- isInterrupted()方法判断是否被中断,终结状态的线程返回false
- 静态方法Thread.interrupted()方法对当前线程的中断位进行复位。
- 抛出InterruptedException之前,JVM会清除线程中断位,所以此时调用isInterrupted()方法返回false
代码示例:
代码语言:javascript复制import java.util.concurrent.TimeUnit;
/**
* SleepThread不停睡眠,BusyThread一直运行,分别中断,观察两者中断标识位
*
* @author pengjunzhe
*/
public class Interrupted {
public static void main(String[] args) throws Exception {
// sleepThread 不停的睡眠
Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
sleepThread.setDaemon(true);
// busyThread 一直运行
Thread busyThread = new Thread(new BusyRunner(), "BusyThread");
busyThread.setDaemon(true);
sleepThread.start();
busyThread.start();
// 休眠5秒,让sleepThread和busyThread充分运行
TimeUnit.SECONDS.sleep(5);
sleepThread.interrupt();
busyThread.interrupt();
System.out.println("SleepThread is " sleepThread.isInterrupted());
System.out.println("BusyThread is " busyThread.isInterrupted());
// 防止两者立刻退出
SleepUtils.second(2);
}
static class SleepRunner implements Runnable {
@Override
public void run() {
while (true) {
SleepUtils.second(10);
}
}
}
static class BusyRunner implements Runnable {
@Override
public void run() {
while (true) {
}
}
}
}
代码输出:
代码语言:javascript复制SleepThread is false
BusyThread is true
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.junzerg.threads.SleepUtils.second(SleepUtils.java:11)
at com.junzerg.threads.Interrupted$SleepRunner.run(Interrupted.java:39)
at java.lang.Thread.run(Thread.java:748)
可以看到,抛出InterruptedException的线程SleepThread的中断位被清除了。运行中的BusyThread中断位没有被清除。