创建线程的三种方式(Thread、Runnable、Callable)

2022-10-17,,,,

 

方式一:继承thread类实现多线程

      1. 在java中负责实现线程功能的类是java.lang.thread 类。

      2. 可以通过创建 thread的实例来创建新的线程。

      3. 每个线程都是通过某个特定的thread对象所对应的方法run( )来完成其操作的,方法run( )称为线程体。

      4. 通过调用thread类的start()方法来启动一个线程(只是将线程由新生态转为就绪态,而不是运行态)。

代码示例:

 1 public class testthread extends thread {//自定义类继承thread类
 2     //run()方法里是线程体
 3     public void run() {
 4         for (int i = 0; i < 10; i++) {
 5             system.out.println(this.getname() + ":" + i);//getname()方法是返回线程名称
 6         }
 7     }
 8  
 9     public static void main(string[] args) {
10         testthread thread1 = new testthread();//创建线程对象
11         thread1.start();//启动线程
12         testthread thread2 = new testthread();
13         thread2.start();
14     }
15 }

此种方式的缺点:因为java只支持单继承多实现,所以当我们的类已经继承了一个类(如小程序必须继承自 applet 类),则无法再继承 thread 类。

方式二:通过runnable接口实现多线程

  在开发中,我们应用更多的是通过runnable接口实现多线程。这种方式克服了实现thread类的缺点,即在实现runnable接口的同时还可以继承某个类。

代码示例:

 1 public class testthread2 implements runnable {//自定义类实现runnable接口;
 2     //run()方法里是线程体;
 3     public void run() {
 4         for (int i = 0; i < 10; i++) {
 5             system.out.println(thread.currentthread().getname() + ":" + i);
 6         }
 7     }
 8     public static void main(string[] args) {
 9         //创建线程对象,把实现了runnable接口的对象作为参数传入;
10         thread thread1 = new thread(new testthread2());
11         thread1.start();//启动线程;
12         thread thread2 = new thread(new testthread2());
13         thread2.start();
14     }
15 }

需要注意的是,start()方法属于thread类的,故自定义类实现runnable接口后调用start()方法前有如下过程:

1 runnable  r = new testthread2();
2 thread thread1 = new thread(r);
3 //简写为:
4 thread thread1 = new thread(new testthread2());

方式三:通过callable接口实现多线程

callable和future出现的原因:

    这2种方式都有一个缺陷就是:在执行完任务之后无法获取执行结果。

    如果需要获取执行结果,就必须通过共享变量或者使用线程通信的方式来达到效果,这样使用起来就比较麻烦。

  而自从java 1.5开始,就提供了callable和future,通过它们可以在任务执行完毕之后得到任务执行结果。

callable和future介绍

  callable接口代表一段可以调用并返回结果的代码;future接口表示异步任务,是还没有完成的任务给出的未来结果。所以说callable用于产生结果,future用于获取结果。

  callable接口使用泛型去定义它的返回类型。executors类提供了一些有用的方法在线程池中执行callable内的任务。由于callable任务是并行的(并行就是整体看上去是并行的,其实在某个时间点只有一个线程在执行),我们必须等待它返回的结果。

  java.util.concurrent.future对象为我们解决了这个问题。在线程池提交callable任务后返回了一个future对象,使用它可以知道callable任务的状态和得到callable返回的执行结果。future提供了get()方法让我们可以等待callable结束并获取它的执行结果。

 callable与runnable

 java.lang.runnable吧,它是一个接口,在它里面只声明了一个run()方法:

1 public interface runnable {
2     public abstract void run();
3 }

由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。

  callable位于java.util.concurrent包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做call():

1 public interface callable<v> {
2     /**
3      * computes a result, or throws an exception if unable to do so.
4      *
5      * @return computed result
6      * @throws exception if unable to compute a result
7      */
8     v call() throws exception;
9 }

可以看到,这是一个泛型接口,call()函数返回的类型就是传递进来的v类型

那么怎么使用callable呢?

一般情况下是配合executorservice来使用的,在executorservice接口中声明了若干个submit方法的重载版本:

<t> future<t> submit(callable<t> task);
<t> future<t> submit(runnable task, t result);
future<?> submit(runnable task);

第一个submit方法里面的参数类型就是callable。

暂时只需要知道callable一般是和executorservice配合来使用的,具体的使用方法讲在后面讲述。

一般情况下我们使用第一个submit方法和第三个submit方法,第二个submit方法很少使用。

future

  future就是对于具体的runnable或者callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。

  future类位于java.util.concurrent包下,它是一个接口:

1 public interface future<v> {
2     boolean cancel(boolean mayinterruptifrunning);
3     boolean iscancelled();
4     boolean isdone();
5     v get() throws interruptedexception, executionexception;
6     v get(long timeout, timeunit unit)
7         throws interruptedexception, executionexception, timeoutexception;
8 }

在future接口中声明了5个方法,下面依次解释每个方法的作用:

cancel方法用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayinterruptifrunning表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论mayinterruptifrunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若mayinterruptifrunning设置为true,则返回true,若mayinterruptifrunning设置为false,则返回false;如果任务还没有执行,则无论mayinterruptifrunning为true还是false,肯定返回true。

iscancelled方法表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。

isdone方法表示任务是否已经完成,若任务完成,则返回true;

get()方法用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;

get(long timeout, timeunit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。

也就是说future提供了三种功能:

  1)判断任务是否完成;

  2)能够中断任务;

  3)能够获取任务执行结果。

  因为future只是一个接口,所以是无法直接用来创建对象使用的,因此就有了下面的futuretask。

futuretask

futuretask实现了runnablefuture接口,这个接口的定义如下:

public interface runnablefuture<v> extends runnable, future<v> {  
    void run();  
} 

可以看到这个接口实现了runnable和future接口,接口中的具体实现由futuretask来实现。这个类的两个构造方法如下 :

1 public futuretask(callable<v> callable) {  
2         if (callable == null)  
3             throw new nullpointerexception();  
4         sync = new sync(callable);  
5     }  
6     public futuretask(runnable runnable, v result) {  
7         sync = new sync(executors.callable(runnable, result));  
8     }  

如上提供了两个构造函数,一个以callable为参数,另外一个以runnable为参数。这些类之间的关联对于任务建模的办法非常灵活,允许你基于futuretask的runnable特性(因为它实现了runnable接口),把任务写成callable,然后封装进一个由执行者调度并在必要时可以取消的futuretask。

  futuretask可以由执行者调度,这一点很关键。它对外提供的方法基本上就是future和runnable接口的组合:get()、cancel、isdone()、iscancelled()和run(),而run()方法通常都是由执行者调用,我们基本上不需要直接调用它。

一个futuretask的例子

 1 public class mycallable implements callable<string> {  
 2     private long waittime;   
 3     public mycallable(int timeinmillis){   
 4         this.waittime=timeinmillis;  
 5     }  
 6     @override  
 7     public string call() throws exception {  
 8         thread.sleep(waittime);  
 9         //return the thread name executing this callable task  
10         return thread.currentthread().getname();  
11     }  
12 }  
 1 public class futuretaskexample {  
 2      public static void main(string[] args) {  
 3         mycallable callable1 = new mycallable(1000);                       // 要执行的任务  
 4         mycallable callable2 = new mycallable(2000);  
 5 
 6         futuretask<string> futuretask1 = new futuretask<string>(callable1);// 将callable写的任务封装到一个由执行者调度的futuretask对象  
 7         futuretask<string> futuretask2 = new futuretask<string>(callable2);  
 8 
 9         executorservice executor = executors.newfixedthreadpool(2);        // 创建线程池并返回executorservice实例  
10         executor.execute(futuretask1);  // 执行任务  
11         executor.execute(futuretask2);    
12 
13         while (true) {  
14             try {  
15                 if(futuretask1.isdone() && futuretask2.isdone()){//  两个任务都完成  
16                     system.out.println("done");  
17                     executor.shutdown();                          // 关闭线程池和服务   
18                     return;  
19                 }  
20 
21                 if(!futuretask1.isdone()){ // 任务1没有完成,会等待,直到任务完成  
22                     system.out.println("futuretask1 output="+futuretask1.get());  
23                 }  
24 
25                 system.out.println("waiting for futuretask2 to complete");  
26                 string s = futuretask2.get(200l, timeunit.milliseconds);  
27                 if(s !=null){  
28                     system.out.println("futuretask2 output="+s);  
29                 }  
30             } catch (interruptedexception | executionexception e) {  
31                 e.printstacktrace();  
32             }catch(timeoutexception e){  
33                 //do nothing  
34             }  
35         }  
36     }  
37 }  

运行如上程序后,可以看到一段时间内没有输出,因为get()方法等待任务执行完成然后才输出内容。

输出结果如下:

futuretask1 output=pool-1-thread-1
waiting for futuretask2 to complete
waiting for futuretask2 to complete
waiting for futuretask2 to complete
waiting for futuretask2 to complete
waiting for futuretask2 to complete
futuretask2 output=pool-1-thread-2
done

 

原文转载地址:ttps://www.sxt.cn/java_jquery_in_action/eleven-runnable-interface.html

       https://www.cnblogs.com/fengsehng/p/6048609.html

《创建线程的三种方式(Thread、Runnable、Callable).doc》

下载本文的Word格式文档,以方便收藏与打印。