美文网首页
创建线程的三种方式

创建线程的三种方式

作者: Crazy_Bear | 来源:发表于2020-07-29 17:28 被阅读0次
    • 直接使用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;
    }
    

    相关文章

      网友评论

          本文标题:创建线程的三种方式

          本文链接:https://www.haomeiwen.com/subject/vnhkrktx.html