首页 > 编程语言 > 详细

Java 实现多线程的三种方式

时间:2019-08-29 15:13:12      阅读:89      评论:0      收藏:0      [点我收藏+]

转载自

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;
    }
}

Java 实现多线程的三种方式

原文:https://www.cnblogs.com/weixuqin/p/11429589.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!