Java 实现多线程的三种方式

转载自

https://www.jianshu.com/p/19f9ce1d82a4

继承 Thread 类

run() 方法 VS start() 方法:

  • run() 方法:普通的成员方法
  • start() 方法:负责启动一个新的线程,并调用 run() 方法
  • 因此启动线程,需要使用 start() 方法
public class MultiThread_Test {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }
}

class MyThread extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

实现 Runnable 接口

实际上 Thread 类也是实现了 Runnable 接口:
class Thread implements Runnable {}

启动 Runnable 实例时,需要放在 Thread 中,然后调用 start() 方法

public class MultiThread_Test {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();
        new Thread(mr).start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

实现 Callable 接口

  • Java 5 开始提供
  • 可以返回结果(通过 Future),也可以抛出异常
  • 需要实现的是 call() 方法
  • 以上两点也是 Callable 接口 与 Runnable 接口的区别
public class MultiThread_Test {
    public static void main(String[] args) throws Exception {
        ExecutorService es = Executors.newSingleThreadExecutor();

        // 自动在一个新的线程上启动 MyCallable,执行 call 方法
        Future<Integer> f = es.submit(new MyCallable());

        // 当前 main 线程阻塞,直至 future 得到值
        System.out.println(f.get());

        es.shutdown();
    }
}

class MyCallable implements Callable<Integer> {
    public Integer call() {
        System.out.println(Thread.currentThread().getName());

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return 123;
    }
}
posted @ 2019-08-29 14:38  希希里之海  阅读(260)  评论(0编辑  收藏  举报