线程的创建

  • Thread类 核心方法为run()和start(). Thread类有一个默认的run()实现,如果要使用自己的run方法,需要通过继承Thread类,重写run方法.
  • Runnable接口 Thread有一个Runnable的变量target,通过Thread(Runnable target)构造方法,可以将自己实现了Runnable接口的类传入Thread,实现线程调用.
  • Callable和FutureTask 使用FutureTask有三个重要的功能:
    1. 取消异步执行中的任务
    2. 判断异步任务是否执行完成
    3. 获取异步任务的执行结果
    public boolean isCancelled() {
        return state >= CANCELLED;
    }
    
    public boolean isDone() {
        return state != NEW;
    }
    
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (!(state == NEW && STATE.compareAndSet
              (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    // in case call to interrupt throws exception
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                    STATE.setRelease(this, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }
    
    /**
     * @throws CancellationException {@inheritDoc}
     */
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
    

FutureTask的构造方法可以将Callable的实现类做入参,Callable的call()方法负责实现Runnable.run()的业务代码,下面是FutureTask中run方法调用call()的实现

public void run() {
    if (state != NEW ||
        !RUNNER.compareAndSet(this, 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);
    }
}
  • 线程池 由Executors工厂类负责创建,通过submit(),execute()方法传入线程实例.这两个方法被Executor接口,ExecutorService接口声明:
public interface Executor {
    void execute(Runnable command);
}

public interface ExecutorService extends Executor {
    Future<?> submit(Runnable task);
    <T> Future<T> submit(Callable<T> task);
}

需要注意的是,execute方法无返回值,submit方法会返回Future接口的实现类,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;
}

小结

创建线程基本的四种方式.