Thread、Runnable和Callable

转载 2015年07月10日 10:36:09

1. 关于Thread的Runnable和Callable接口

其实非常简单:其实他们的区别就是Callable有返回值并且可以抛出异常。





/**
 * Represents a command that can be executed. Often used to run code in a
 * different {@link Thread}.
 */
public interface Runnable {


    /**
     * Starts executing the active part of the class' code. This method is
     * called when a thread is started that has been created with a class which
     * implements {@code Runnable}.
     */
    public void run();
}



/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * <tt>call</tt>.
 *
 * <p>The <tt>Callable</tt> interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * <tt>Runnable</tt>, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p> The {@link Executors} class contains utility methods to
 * convert from other common forms to <tt>Callable</tt> classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method <tt>call</tt>
 */
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}


2. Thread类

 1、Runnable接口源码:

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

  2、Thread类与Runnable接口的继承关系

1 public class Thread implements Runnable{
2 
3 }

  Runnable接口仅有一个run()方法,Thread类实现了Runnable接口。

  3、构造函数

1 public Thread() {
2     init(null, null, "Thread-" + nextThreadNum(), 0);
3 }
1 public Thread(Runnable target) {
2     init(null, target, "Thread-" + nextThreadNum(), 0);
3 }
1 public Thread(ThreadGroup group, Runnable target) {
2     init(group, target, "Thread-" + nextThreadNum(), 0);
3 }
1 public Thread(String name) {
2     init(null, null, name, 0);
3 }
                  还有其它的构造方法,此处省略。。。

  这里的第三个参数是设置线程的名称,从下面的代码中可以看出,生成名称的规则是:”Thread-”加上创建的线程的个数(第几个)。

继续查看init方法:

复制代码
 1 /**
 2      * Initializes a Thread.
 3      *
 4      * @param g the Thread group
 5      * @param target the object whose run() method gets called
 6      * @param name the name of the new Thread
 7      * @param stackSize the desired stack size for the new thread, or
 8      *        zero to indicate that this parameter is to be ignored.
 9      */
    //ThreadGroup:线程组表示一个线程的集合。此外,线程组也可以包含其他线程组。线程组构成一棵树,在树中,除了初始线程组外,每个线程组都有一个父线程组。  10 private void init(ThreadGroup g, Runnable target, String name, 11 long stackSize) { 12 Thread parent = currentThread(); 13 SecurityManager security = System.getSecurityManager(); 14 if (g == null) { 15 /* Determine if it's an applet or not */ 16 17 /* If there is a security manager, ask the security manager 18 what to do. */ 19 if (security != null) { 20 g = security.getThreadGroup(); 21 } 22 23 /* If the security doesn't have a strong opinion of the matter 24 use the parent thread group. */ 25 if (g == null) { 26 g = parent.getThreadGroup(); 27 } 28 } 29 30 /* checkAccess regardless of whether or not threadgroup is 31 explicitly passed in. */ 32 g.checkAccess(); 33 34 /* 35 * Do we have the required permissions? 36 */ 37 if (security != null) { 38 if (isCCLOverridden(getClass())) { 39 security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION); 40 } 41 } 42 43 44 g.addUnstarted(); 45 46 this.group = g;

    //每个线程都有一个优先级,高优先级线程的执行优先于低优先级线程。每个线程都可以或不可以标记为一个守护程序。当某个线程中运行的代码创建一个新 Thread 对象时,该新线程的初始优先级被设定为创建线程的优先级,并且当且仅当创建线程是守护线程时,新线程才是守护程序。 

47     this.daemon = parent.isDaemon();
48     this.priority = parent.getPriority();
49     this.name = name.toCharArray();
50     if (security == null || isCCLOverridden(parent.getClass()))
51         this.contextClassLoader = parent.getContextClassLoader();
52     else
53         this.contextClassLoader = parent.contextClassLoader;
54     this.inheritedAccessControlContext = AccessController.getContext();
55     this.target = target;
56     setPriority(priority);
57         if (parent.inheritableThreadLocals != null)
58         this.inheritableThreadLocals =
59         ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
60         /* Stash the specified stack size in case the VM cares */
61         this.stackSize = stackSize;
62 
63         /* Set thread ID */
64         tid = nextThreadID();
65     }
复制代码

  初始化时设置了是否为守护线程,优先级,初始化名称。

  4、Thread的start方法的实现:

复制代码
 1 public synchronized void start() {
 2         /**
 3      * This method is not invoked for the main method thread or "system"
 4      * group threads created/set up by the VM. Any new functionality added 
 5      * to this method in the future may have to also be added to the VM.
 6      *
 7      * A zero status value corresponds to state "NEW".
 8          */
 9         if (threadStatus != 0)
10             throw new IllegalThreadStateException();
11         group.add(this);
12         start0();
13         if (stopBeforeStart) {
14         stop0(throwableFromStop);
15     }
16 }
复制代码

  这里主要的是start0方法;查看其实现:

 1 private native void start0();

  这里使用了本地调用,通过C代码初始化线程需要的系统资源。可见,线程底层的实现是通过C代码去完成的。

4、Thread的run方法的实现

1 public void run() {
2     if (target != null) {
3         target.run();
4     }
5 }

  这里的target实际上要保存的是一个Runnable接口的实现的引用:

1 private Runnable target;

  所以使用继承Thread创建线程类时,需要重写run方法,因为默认的run方法什么也不干。

  而当我们使用Runnable接口实现线程类时,为了启动线程,需要先把该线程类实例初始化一个Thread,实际上就执行了如下构造函数:

1 public Thread(Runnable target) {
2     init(null, target, "Thread-" + nextThreadNum(), 0);
3 }

  即是把线程类的引用保存到target中。这样,当调用Thread的run方法时,target就不为空了,而是继续调用了target的run方法,所以我们需要实现Runnable的run方法。这样通过Thread的run方法就调用到了Runnable实现类中的run方法。

  这也是Runnable接口实现的线程类需要这样启动的原因。



另外java中的Executor 类也是非常简单的接口,只有一个execute()方法

   public interface Executor {


    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the <tt>Executor</tt> implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution.
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

     Excutor执行已提交的 Runnable 任务的对象。此接口提供一种将任务提交与每个任务将如何运行的机制(包括线程使用的细节、调度等)分离开来的方法。通常使用 Executor 而不是显式地创建线程。例如,可能会使用以下方法,而不是为一组任务中的每个任务调用 new Thread(new(RunnableTask())).start()

 Executor executor = anExecutor;
 executor.execute(new RunnableTask1());
 executor.execute(new RunnableTask2());
 ...
 
不过,Executor 接口并没有严格地要求执行是异步的。在最简单的情况下,执行程序可以在调用方的线程中立即运行已提交的任务:
 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }
更常见的是,任务是在某个不是调用方线程的线程中执行的。以下执行程序将为每个任务生成一个新线程。
 class ThreadPerTaskExecutor implements Executor {
     public void execute(Runnable r) {
         new Thread(r).start();
     }
 }
许多 Executor 实现都对调度任务的方式和时间强加了某种限制。以下执行程序使任务提交与第二个执行程序保持连续,这说明了一个复合执行程序。
 class SerialExecutor implements Executor {
     final Queue<Runnable> tasks = new LinkedBlockingQueue<Runnable>();
     final Executor executor;
     Runnable active;

     SerialExecutor(Executor executor) {
         this.executor = executor;
     }

     public synchronized void execute(final Runnable r) {
         tasks.offer(new Runnable() {
             public void run() {
                 try {
                     r.run();
                 } finally {
                     scheduleNext();
                 }
             }
         });
         if (active == null) {
             scheduleNext();
         }
     }

     protected synchronized void scheduleNext() {
         if ((active = tasks.poll()) != null) {
             executor.execute(active);
         }
     }
 }

java入门学习:多线程创建-Thread,Runnable,callable和threadpool

java创建多线程的方式有许多种,这里简要做个梳理1. 继承Thread类 继承java.lang.Thread类,创建本地多线程的类,重载run()方法,调用Thread的方法启动线程。示例代码如...

Java多线程Thread,Runnable, Callable<>和线程池(一)

这一篇主要关注于我们自己实现和管理多线程,后面会介绍使用线程池实现多线程。 Java里面实现多线程有三种方式,继承 Thead类,或者实现Runnable和Callable接口。下面详细介绍一下这三...

java多线程—Runnable、Thread、Callable

多线程编程优点: 进程之间不能共享内存,但线程之间共享内存非常容易。系统创建线程所分配的资源相对创建进程而言,代价非常小。 Java中实现多线程有3种方法: 继承Thread类实现Runnable...

java 创建线程的三种方法Callable,Runnable,Thread比较及用法

编写多线程程序是为了实现多任务的并发执行,从而能够更好地与用户交互。一般有三种方法,Thread,Runnable,Callable. Runnable和Callable的区别是, (1)Call...

Thread、Runnable、Callable三种创建线程的简单示例及区别简介

一、继承Thread类 1、编写线程类,继承Thread类 2、重写run()方法 把该线程需要完成的任务代码写在run()中,也称为线程体 3...

线程的初步理解,生命周期,实现方法,Thread类,Runnable接口,Callable接口线程池

=======================第一节课开始============================================= ###01进程概念 *A:进程概念  ...

java实现多线程的三种方式(thread、runnable、callable)

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没...

Java中Runnable和Thread以及Callable的区别

在java中,其实java中实现 多线程有三种方法,一种是继承Thread类;第二种是实现Runnable接口;第三种是实现Callable接口。1,继承Thread        Thread类是在...

安卓复习之旅—Thread、Runnable、Callable、Futrue类关系与区别

开启一个线程有三种方式定义:Thread、Runnable、Callable,其中Runnable实现的是void run()方法,Callable实现的是 V call()方法,并且可以返回执行结果...
  • lin_t_s
  • lin_t_s
  • 2016年12月07日 11:29
  • 240

多线程相关 Thread、Runnable、Callable、Futrue类关系与区别

Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Thread、Runnable和Callable
举报原因:
原因补充:

(最多只允许输入30个字)