java并发(一)线程创建三种方式与优缺点

三种实现线程的方法

  • 继承Thread类,重写run方法

  • 实现Runnable接口,重写run方法

  • 实现Callable<>接口,重写call方法,使用FutureTask方式

  • 代码

package day0122;

import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author Braylon
 * @Date 2020/1/22 9:31
 */
public class threeWays {
    public static class thread1 extends Thread {
        @Override
        public void run() {
            System.out.println("child thread: extends Thread to realise concurrent");
        }
    }

    public static class thread2 implements Runnable {
        public void run() {
            System.out.println("child thread2: implements Runnable to realise concurrent");
        }
    }

    public static class thread3 implements Callable<String> {
        public String call() throws Exception {
            return "this is third method Callable to realize concurrent";
        }
    }

    @Test
    public void test() {
//        thread1 thread1 = new thread1();
//        thread1.start();
//
//        thread2 thread2 = new thread2();
//        new Thread(thread2).start();
//        new Thread(thread2).start();

        FutureTask<String> stringfuturetask = new FutureTask<>(new thread3());
        new Thread(stringfuturetask).start();
        try {
            String s = stringfuturetask.get();
            System.out.println("thread3: " + s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

优缺点

  • 继承THread

优点:
使用继承 的方式方便传参,可以在子类里面添加成员变量,通过set方法设置参数或者通过构造函数进行传递
缺点:
java不支持多继承,也就是当继承了Thread类后不能再继承其他类。任务与代码没有分离,当多个线程执行一样的任务时需要多个任务代码。

  • 实现Runnable接口

优点:可以继承其他类,也可以添加参数进行任务分区。
缺点:
这两种方法都有一个缺点就是任务没有返回值。

  • 使用FutureTask方式

优点:
可以得到任务的返回结果。

发布了31 篇原创文章 · 获赞 33 · 访问量 2833

猜你喜欢

转载自blog.csdn.net/qq_40742298/article/details/104074550
今日推荐