Java-多线程

来源:互联网 发布:html5手机游戏源码 编辑:程序博客网 时间:2024/05/06 09:23

多线程实现的方式主要有3种:

一、继承Thread,重写run()函数

     class A extends Thread{

      public void run0{};

      }

      new A().start();


二、实现runnable接口,重写run()函数

     class A implements Runnable{

     public void run(){};

     }

     new Thread(new A()).start();


三、实现Callable接口,重写call函数

     Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。

     不同点:

                   ①:Callable重写的方法是call(),Runnable实现的方法是run();

                   ②:Callable执行任务后有返回值,Runnable执行任务后无返回值;

                   ③:call()方法可抛出异常,run()方法是不会抛出异常的;

                   ④:运行callable任务可以拿到一个Future对象,Future表示异步的计算结果,它提供了检查计算任务是否完成,以及继续完成任务的时间,并检索计算的结果。


eg:

      

  1. class TaskWithResult implements Callable<String> {  
  2.     private int id;  
  3.   
  4.     public TaskWithResult(int id) {  
  5.         this.id = id;  
  6.     }  
  7.   
  8.     @Override  
  9.     public String call() throws Exception {  
  10.         return "result of TaskWithResult " + id;  
  11.     }  
  12. }  
  13.   
  14. public class CallableTest {  
  15.     public static void main(String[] args) throws InterruptedException,  
  16.             ExecutionException {  
  17.         ExecutorService exec = Executors.newCachedThreadPool();  
  18.         ArrayList<Future<String>> results = new ArrayList<Future<String>>();    //Future 相当于是用来存放Executor执行的结果的一种容器  
  19.         for (int i = 0; i < 10; i++) {  
  20.             results.add(exec.submit(new TaskWithResult(i)));  
  21.         }  
  22.         for (Future<String> fs : results) {  
  23.             if (fs.isDone()) {  
  24.                 System.out.println(fs.get());  
  25.             } else {  
  26.                 System.out.println("Future result is not yet complete");  
  27.             }  
  28.         }  
  29.         exec.shutdown();  
  30.     }  


0 0
原创粉丝点击