Java创建线程的方式有三种:
1.继承Thread
2.实现Runnable
3.实现Callable
继承Thread
继承Thread类并重写其void run方式即可新建一个线程,启动调用Thread.start()方法。
Thread thread = new Thread(()->{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info(Thread.currentThread().getName()+"thread线程执行");
});
thread.start();
实现Runnable
Runnable接口提供了一个void run接口,实现该方法定义线程,但运行其线程,还需要将其传递给Thread类,调用Thread.start()运行线程。
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("runnable 线程执行" + Thread.currentThread().getName());
}
};
//runnable依赖Thread执行
new Thread(runnable).start();
实现Callable
无论是继承Thread还是实现Runnable接口创建的线程都是没有返回值的,如果需要返回值,则需要实现Callable创建线程。
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
System.out.println("callable线程" + Thread.currentThread().getName());
return "callable线程" + Thread.currentThread().getName();
}
};
但callable本是没有提供运行线程的方法,Thread的构造函数也没有接受Callable类型的,因此要运行Callable创建的线程,需要借助FutureTask类。
FutureTask<String> stringFutureTask = new FutureTask<>(callable);
new Thread(stringFutureTask).start();
可以通过FutureTask的get方法获取线程执行结果,如果线程没有执行完,则会一直阻塞。
stringFutureTask.get();
FutureTask
FutureTask实现RunnableFuture接口,RunableFuture接口继承了Runnable、Future接口。RunableFuture本是没有实现任何功能。
public interface RunnableFuture<V> extends Runnable, Future<V> {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
Future接口定义了线程的一系列方法,如获取线程运行结果、查看线程是否执行完毕、取消线程、查询线程是否已取消。
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
FutureTask实现了RunableFuture的run方法和Future接口的一系列方法,首先看看FutureTask这个类成员变量
private volatile int state;
private static final int NEW = 0;
private static final int COMPLETING = 1;
private static final int NORMAL = 2;
private static final int EXCEPTIONAL = 3;
private static final int CANCELLED = 4;
private static final int INTERRUPTING = 5;
private static final int INTERRUPTED = 6;
/** The underlying callable; nulled out after running */
private Callable<V> callable;
/** The result to return or exception to throw from get() */
private Object outcome; // non-volatile, protected by state reads/writes
/** The thread running the callable; CASed during run() */
private volatile Thread runner;
/** Treiber stack of waiting threads */
private volatile WaitNode waiters;
其中使用volatile修饰的state变量表示线程的状态,在这里线程的状态分为以下几个:
1.New 线程初始状态
2.COMPLETING 线程由NEW转变为NORMAL或EXCEPTIONAL的中间状态
3.NORMAL 线程正常结束的状态
4.EXCEPTIONAL 线程因异常结束的状态
5.CANCELLED 线程取消状态
6.INTERRUPTING 线程由NEW转变为INTERRUPTED的中间状态
7.INTERRUPTED 线程中断状态
状态关系图如下:
FutureTask其他的Callable变量表示传入的Callable线程实现、outcome表示线程的执行结果,其中runner表示当前运行线程、waiter表示等待线程,等待线程类型是内部类WaitNode,如下:
static final class WaitNode {
volatile Thread thread;
volatile WaitNode next;
WaitNode() { thread = Thread.currentThread(); }
}
类似链表,存储的是当前线程和下一个等待线程,在线程执行没有结束时,获取线程的结果的线程都会被放入该链表,当运行线程执行结束时,会依次唤醒等待线程。
首先来看FutureTask的构造函数:
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
传入Callable,并设置state为初始状态NEW,紧接着看看run方法:
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
执行流程如下:
1.首先判断当前状态是否为NEW,同时利用CAS判断当前类的runnerOffset偏移量是否为null,这两个判断都是用于验证当前线程是否在执行中。其中偏移量参数的初始化放在了static代码块里。如:
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
private static final long runnerOffset;
private static final long waitersOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = FutureTask.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
runnerOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("runner"));
waitersOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("waiters"));
} catch (Exception e) {
throw new Error(e);
}
}
2.接着检查传入的callable对象是null同时state的状态,为真执行callable的call方法,将ran的值设置为true,该变量的作用是标识线程是否是正常结束还是异常结束
3.如果发送异常,result结果值为null,ran为FALSE,执行setException方法
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = t;
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
该方法的逻辑就是变更state状态 由new->completing->exceptional,同时调用finishCompletion()将waiter等待链表的线程全部唤醒,并将waiter初始化。
private void finishCompletion() {
// assert state > COMPLETING;
for (WaitNode q; (q = waiters) != null;) {
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
for (;;) {
Thread t = q.thread;
if (t != null) {
q.thread = null;
LockSupport.unpark(t);
}
WaitNode next = q.next;
if (next == null)
break;
q.next = null; // unlink to help gc
q = next;
}
break;
}
}
done();
callable = null; // to reduce footprint
}
4.如果正常结束,执行set(result)方法
protected void set(V v) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
outcome = v;
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
finishCompletion();
}
}
该方法的逻辑就是将stateOffset转变为 NEW->COMPLETING->NORMAL ,再唤醒等待链表,初始化waiter
5.最后finally执行结尾操作,将运行线程runner置为null,判断当前状态,如果是中断或者正在中断的话 让出该线程的时间片,让线程恢复为就绪状态,准备中断。 提高系统吞吐量。
除此之外,futuretask的get()方法如下:
public V get() throws InterruptedException, ExecutionException {
//获取状态
int s = state;
//如果运行线程还没未执行结束
if (s <= COMPLETING)
//等待线程执行完毕
s = awaitDone(false, 0L);
//直接返回线程执行结果
return report(s);
}
其中awaitDone方法是将当前获取线程执行结果的线程阻塞等待。具体分析如下:
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
//获取等待时间
final long deadline = timed ? System.nanoTime() + nanos : 0L;
//
WaitNode q = null;
boolean queued = false;
for (;;) {
//如果出现线程中断信息则移除等待链表的节点信息,并抛出异常
if (Thread.interrupted()) {
removeWaiter(q);
throw new InterruptedException();
}
//获取执行线程状态
int s = state;
//如果线程执行完毕
if (s > COMPLETING) {
//将等待节点的线程置为null
if (q != null)
q.thread = null;
//直接返回状态
return s;
}
//表示当前执行线程快执行完了,当前线程让出cpu 恢复为就绪状态等待
else if (s == COMPLETING) // cannot time out yet
Thread.yield();
//如果任务还在执行或还未执行则构建waitnode节点
else if (q == null)
q = new WaitNode();
// 利用cas机制将构建好的waitnode节点加入逻辑链表
// 注意:该链表是栈的结构,所以并不是将新的节点
// 变为之前节点的next,而是新节点变为head节点
// 旧节点变为next后继节点(这样方便维护逻辑链表结构)
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
//如果是超时等待模式 则判断是否超时
//超时则移除等待节点直接返回状态
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
//未超时 则挂起相应时间
LockSupport.parkNanos(this, nanos);
}
else
//正常则挂起线程
LockSupport.park(this);
}
}