java多线程的三种实现方式

第一种 实现Runnable接口,覆写run()方法

第二种 继承Thread类,覆写run()方法

第三种 利用Callable接口、Executors工具类、ExecutorService接口、Future接口实现有返回结果的多线程


 

 

第一种 实现Runnable接口,覆写run()方法

 

① 自定义类并实现Runnable接口,覆写run()方法

② 创建Thread对象,用实现了Runnable接口的类的实例对象作为参数实例化该Thread对象

③ 调用Thread的start()方法来启动线程

 1 package com.test;
 2 
 3 class MyThread implements Runnable{  // ①
 4     @Override
 5     public void run() {
 6         System.out.println("Thread body");
 7     }
 8 }
 9 public class MultiThread {
10     public static void main(String[] args){
11         Thread thread1 = new Thread(new MyThread());  // ②
12         Thread thread2 = new Thread(new MyThread());
13         thread1.start();  // ③
14         thread2.start();
15     }
16 }

 

第二种  继承Thread类,覆写run()方法

① 自定义类并继承Thread类,覆写run()方法

② 创建自定义类的实例对象

③ 调用自定义类对象的start()方法来启动线程

 1 package com.test;
 2 
 3 class MyThread extends Thread{  // ①
 4     @Override
 5     public void run() {
 6         System.out.println("Thread body");
 7     }
 8 }
 9 public class MultiThread {
10     public static void main(String[] args){
11         Thread thread1 = new MyThread();  // ②
12         Thread thread2 = new MyThread();
13         thread1.start();  // ③
14         thread2.start();
15     }
16 }

 第三种 利用Callable接口、Executors工具类、ExecutorService接口、Future接口实现有返回结果的多线程

① 自定义类实现Callable接口,并覆写call()方法

② 利用Executors创建一个线程池 ExecutorService接口的实例对象

③ 调用线程池的submit()方法来启动线程,该方法会返回一个Future接口的实例对象

④ 调用Future实例对象的get()方法,获得线程的返回结果

 1 package com.test;
 2  
 3 import java.util.concurrent.*;
 4  
 5 class MyThread implements Callable<String>{  // ① 创建线程
 6      @Override
 7      public String call() {
 8          return "Thread body";
 9      }
10 }
11 public class MultiThread3 {
12     public static void main(String[] args){
13         ExecutorService threadPool = Executors.newSingleThreadExecutor();  // ② 创建线程池
14         Future<String> future = threadPool.submit(new MyThread());  // ③ 想线程池提交任务
15         try {
16             System.out.println(future.get());  // ④ 获得return的值
17         } catch (InterruptedException | ExecutionException e) {
18             e.printStackTrace();
19         }
20         threadPool.shutdown()  // 关闭线程池
21     }
22 }

 


 

Callable接口提供了比Runnable接口更强大的功能

1)Callable接口的call()方法可以在任务结束后提供一个返回值,Runnable接口的run()方法无法提供这个功能

2)Callable接口的call()方法可以抛出异常,Runnable接口的run()方法无法提供这个功能

3)ExecutorService接口的submit()方法可以得到一个Future接口的实例对象,可使用Future对象来监视目标线程调用call()方法的情况,当调用Future对象的get()方法以获取结果时,当前线程会阻塞,知道call()方法结果返回结果。

以上三种方式中,前两种方式线程执行完后没有返回值,只有第三种方式是带返回值的

当需要实现多线程时,一般推荐实现Runnable接口的方式

posted on 2018-09-06 01:35  0820LL  阅读(320)  评论(0编辑  收藏  举报

导航