一直以为实现线程的方式有三种extends Thread,import Runnable, Callable,
然后有一天看到了jdk源码里面的注释
*There are two ways to create a new thread of execution. One is to
* declare a class to be a subclass of <code>Thread</code>. This
* subclass should override the <code>run</code> method of class
* <code>Thread</code>. An instance of the subclass can then be
* allocated and started. For example, a thread that computes primes
* larger than a stated value could be written as follows:
* <hr><blockquote><pre>
* class PrimeThread extends Thread {
* long minPrime;
* PrimeThread(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeThread p = new PrimeThread(143);
* p.start();
* </pre></blockquote>
* <p>
* The other way to create a thread is to declare a class that
* implements the <code>Runnable</code> interface. That class then
* implements the <code>run</code> method. An instance of the class can
* then be allocated, passed as an argument when creating
* <code>Thread</code>, and started. The same example in this other
* style looks like the following:
* <hr><blockquote><pre>
* class PrimeRun implements Runnable {
* long minPrime;
* PrimeRun(long minPrime) {
* this.minPrime = minPrime;
* }
*
* public void run() {
* // compute primes larger than minPrime
* . . .
* }
* }
* </pre></blockquote><hr>
* <p>
* The following code would then create a thread and start it running:
* <blockquote><pre>
* PrimeRun p = new PrimeRun(143);
* new Thread(p).start();
* </pre></blockquote>
* <p>
* Every thread has a name for identification purposes. More than
* one thread may have the same name. If a name is not specified when
* a thread is created, a new name is generated for it.
jdk的源码里面只提到了Thread和Runnable,为什么没有提Callable呢,
下面我们看下Callable实现线程的方式
public static void main(String[] args) throws InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask<MyCallable> ft = new FutureTask<>(myCallable);
Thread thread = new Thread(ft);
thread.start();
}
private static class MyCallable implements Callable{
@Override
public Object call() throws Exception {
return "callAble";
}
}
可以看到callable的实现是通过FutureTask实现的,而FutureTask实际上是实现的 RunnableFuture
因为用的是社区版的idea,没有类的继承图,所以类的继承图就懒得弄了,大家有兴趣的可以自己去看看。