创建线程的三种方式

  • 直接使用Thread
    使用匿名内部类
Thread thread = new Thread(“线程名字”) {
            @Override
            public void run(){
                //指定任务
            }
        };
  • 使用Runnable 配合Thread
Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //指定任务
            }
        };
        new Thread(runnable).start();
    }

由于Runable有FuctionalInterferce注释,lambda简化

Thread thread = new Thread(() -> {
//指定任务
}); //Java8

使用Runnable方法初始化Thread时,会将Runnable对象赋值给Thread的成员变量private Runnable target,Thread的run方法源码如下:

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

由此可知如果Runnable存在,会优先调用Runnable的run方法。
使用Runable可以将线程和任务分开,让任务类脱离了线程的继承关系,更灵活。(组合优于继承)

  • FutureTask配合Thread
    FutureTask可接受Callable参数,用来处理带返回结果的情况
 FutureTask<Integer> task = new FutureTask<>(() -> {
            //操作
            return 1;
        });
        new Thread(task,"线程名字").start();
        //主线程阻塞(其他线程正常运行),同步等待task的执行结果
        Integer result = task.get();

继承关系如下:
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
Callable接口源码:

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。