从线程工厂到线程
工厂模式中有四个角色:
- Factory:抽象的工厂
- Product:抽象的零件
- 具体的实现工厂
- 具体的实现零件
上图就是一个工厂模式。
线程池是一个工厂,线程是线程池中的零件。
抽象工厂
public interface ThreadFactory {
/**
* Constructs a new {@code Thread}. Implementations may also initialize
* priority, name, daemon status, {@code ThreadGroup}, etc.
*
* @param r a runnable to be executed by new thread instance
* @return constructed thread, or {@code null} if the request to
* create a thread is rejected
*/
Thread newThread(Runnable r);
}
该线程工厂中有一个方法为生产一个新的线程。
线程工厂
static class DefaultThreadFactory implements ThreadFactory {
//线程池大小为1
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();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
创建新线程,设置为用户线程,和默认的线程优先级。
线程
group – the thread group. If null and there is a security manager, the group is determined by SecurityManager.getThreadGroup(). If there is not a security manager or SecurityManager.getThreadGroup() returns null, the group is set to the current thread’s thread group.
线程组
target – the object whose run method is invoked when this thread is started. If null, this thread’s run method is invoked.
调用的run方法
name – the name of the new thread
线程名字
stackSize – the desired stack size for the new thread, or zero to indicate that this parameter is to be ignored.
堆栈大小
public Thread(ThreadGroup group, Runnable target, String name,
long stackSize) {
init(group, target, name, stackSize);
}
线程的参数
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
线程优先级为1-10,5为默认优先级。
//是否 为守护线程
private boolean daemon = false;
//run方法
private Runnable target;
//线程的线程组
private ThreadGroup group;
//上下文类加载器
private ClassLoader contextClassLoader;
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
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.ThreadLocalMap inheritableThreadLocals = null;
//堆栈值
private long stackSize;
/*
* JVM-private state that persists after native thread termination.
*/
private long nativeParkEventPointer;
//线程ID
private long tid;
//线程生成ID
private static long threadSeqNumber;
/* Java thread status for tools,
* initialized to indicate thread 'not yet started'
*/
private volatile int threadStatus = 0;
Run和Start方法
//从线程开始执行,JAVA虚拟机会调用该线程的run方法,然后两个线程同时执行
//线程只能启动一次,完成后不能重新启动
public synchronized void start() {
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 */
}
}
}
private native void start0();
//线程是单独的一个Runnable对象,则会被调用,否则不做任何事情
@Override
public void run() {
if (target != null) {
target.run();
}
}
从线程开始执行,jvm会调用该线程的run方法,然后两个线程同时执行
线程只能启动一次,完成后不能重新启动
线程启动调用了start0的本地方法,所以是jvm来调用的
线程的状态
public enum State {
//线程的初始态
NEW,
//运行态
RUNNABLE,
//阻塞态
BLOCKED,
//等待
WAITING,
//等待超时
TIMED_WAITING,
//终止态
TERMINATED;
}
线程的6个状态。