美文网首页
Concurrency: Thread类及Runnable接口的

Concurrency: Thread类及Runnable接口的

作者: CalmHeart | 来源:发表于2019-05-22 21:38 被阅读0次
    • Thread类:

    • 声明: public class Thread implements Runnable

    • 从Java doc的层面了解Thread类及Runnable接口

    • 一个Thread指的是程序当中一个执行线程,Java虚拟机允许一个应用拥有多个并发执行的线程
      A <i>thread</i> is a thread of execution in a program. The Java
      Virtual Machine allows an application to have multiple threads of
      execution running concurrently.

    • 每一个线程都拥有一个优先级,拥有更高优先级的线程要优先于优先级低的线程执行,一个线程可能标记成或不标记成一个demon线程 当运行在一些线程中的代码创建了一个新的Thread对象的话,这个新的线程的优先级与这个创建线程的优先级一致 只有创建线程是demon线程的时候 这个被创建的线程才是demon线程

    Every thread has a priority. Threads with higher priority are
    executed in preference to threads with lower priority. Each thread
    may or may not also be marked as a daemon. When code running in
    some thread creates a new <code>Thread</code> object, the new
    thread has its priority initially set equal to the priority of the
    creating thread, and is a daemon thread if and only if the
    creating thread is a daemon.

    • 当Java虚拟机启动的时候 通常存在单个非demon的线程(通常调用一个被指定类的main方法)Java虚拟机会继续执行线程直到下面的两种情况发生:

    When a Java Virtual Machine starts up, there is usually a single
    non-daemon thread (which typically calls the method named
    <code>main</code> of some designated class). The Java Virtual
    Machine continues to execute threads until either of the following
    occurs:

    • Runtime类的exit方法被调用,并且安全管理器允许exit操作执行
      <li>The <code>exit</code> method of class <code>Runtime</code> has been called and the security manager has permitted the exit operation to take place.

    • 所有的非demon线程都已经消亡了,调用run方法返回了或者在执行run方法的时候抛出异常(传播到run方法的外面)
      All threads that are not daemon threads have died, either by
      returning from the call to the <code>run</code> method or by
      throwing an exception that propagates beyond the <code>run</code> method.

    • 有两种创建线程的方式:一种是声明一个继承自Thread的子类,这个子类必须重写Thread类的run方法,一个子类的实例可以被分配并启动,比如一个用于计算primes大于一个状态值的线程可以被写成如下形式:
      There are two ways to create a new thread of execution. One is to
      declare a class to be a subclass of <code>Thread</code>. This
      subclass should override the <code>run</code> method of class <code>Thread</code>. An instance of the subclass can then be
      allocated and started. For example, a thread that computes primes
      larger than a stated value could be written as follows:

         class PrimeThread extends Thread {
               long minPrime;
               PrimeThread(long minPrime) {
               this.minPrime = minPrime;
              }
     
              public void run() {
                  // compute primes larger than minPrime
                  &nbsp;.&nbsp;.&nbsp;.
              }
          }
    
    • 下面的代码将创建一个线程并启动运行
      The following code would then create a thread and start it running:
          PrimeThread p = new PrimeThread(143);
          p.start();
    
    • 另一种创建线程的方式是通过声明一个类实现Runnable接口 这个类将会实现run方法 这个类的实例可以被分配,将其自身作为参数将其传递给Thread构造器并启动

    The other way to create a thread is to declare a class that
    implements the <code>Runnable</code> interface. That class then
    implements the <code>run</code> method. An instance of the class can
    then be allocated, passed as an argument when creating
    <code>Thread</code>, and started. The same example in this other
    style looks like the following:

    • 示例代码如下:
       class PrimeRun implements Runnable {
             long minPrime;
             PrimeRun(long minPrime) {
                 this.minPrime = minPrime;
             }
    
            public void run() {
                // compute primes larger than minPrime
                &nbsp;.&nbsp;.&nbsp;.
          }
        }
    
    • The following code would then create a thread and start it running:
        PrimeRun p = new PrimeRun(143);
        new Thread(p).start();
    
    • 每一个线程都有一个名字用于唯一标识的目的,多个线程可以拥有相同的名字,当一个线程被创建的时候如果没有被指定一个名称,一个新的名字会被指定

    Every thread has a name for identification purposes. More than
    one thread may have the same name. If a name is not specified when
    a thread is created, a new name is generated for it.

    • 除非有特别的说明 否则将null作为参数传递给Thread类的构造器会导致NPE抛出
      Unless otherwise noted, passing a {@code null} argument to a constructor or method in this class will cause a {@link NullPointerException} to be thrown.

    • 核心属性:

      • 最小的优先级
        The minimum priority that a thread can have.
        public final static int MIN_PRIORITY = 1;
      • 默认的优先级
        The default priority that is assigned to a thread.
        public final static int NORM_PRIORITY = 5;
      • 最大的优先级
        The maximum priority that a thread can have.
        public final static int MAX_PRIORITY = 10;
    • 核心方法:

      1. currentThread方法签名:java.lang.Thread @NotNull
        @Contract(pure = true)
        public static Thread currentThread()
    • 说明:

    • 获取当前正在执行的线程
      Returns a reference to the currently executing thread object.

      1. init方法签名:
        private void init(ThreadGroup g, Runnable target, String name,
        long stackSize, AccessControlContext acc,
        boolean inheritThreadLocals)
      1. start方法签名:public synchronized void start()
    • 说明:

    • 导致这个线程开始执行,Java虚拟机调用这个线程的run方法,结果是两个线程并发的执行,当前的线程(调用start方法返回的线程)及另外一个线程(调用run方法的线程),多次调用start方法是不合法的,特别地,一个线程一旦执行完成就不可能重新启动

    Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

      1. run方法签名:public void run()
    • 说明:
    • 如果这个线程使用Runnable的方式进行构建,那么这个Runnable对象的run方法会被调用,否则这个方法什么都不做
      If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
    • Thread的子类应该重写这个方法
      Subclasses of Thread should override this method.

    • Runnable接口:
    • 声明:

    @FunctionalInterface 显示指定为函数式接口
    public interface Runnable

    • Runnble接口应该被任何试图通过一个线程执行的实例实现,这个类必须定义一个无参的run方法
      The <code>Runnable</code> interface should be implemented by any
      class whose instances are intended to be executed by a thread. The
      class must define a method of no arguments called <code>run</code>.

    • 这个接口为那些当它们处于激活状态想要去执行一些代码的对象提供一个通用的协议 例如:Thread类实现Runnable接口
      This interface is designed to provide a common protocol for objects that
      wish to execute code while they are active. For example, <code>Runnable</code> is implemented by class <code>Thread</code>.

    • 处于激活状态的简单理解是一个线程已经被启动但还未被停止
      Being active simply means that a thread has been started and has not
      yet been stopped.

    • 此外 Runnable为一个类提供了一种不通过子类化Thread类的方式让它处于活动状态 一个类可以通过实现Runnable接口 而不是通过子类化一个Thread的方式 通过将实例化一个Thread 并将其自身作为目标传递进去作为Thread实例的一个参数

    In addition, <code>Runnable</code> provides the means for a class to be active while not subclassing <code>Thread</code>. A class that implements <code>Runnable</code> can run without subclassing <code>Thread</code> by instantiating a <code>Thread</code> instance and passing itself in as the target.

    • 最佳实践:

    • 大多数情况下 如果仅仅打算去重写run方法而不重写Thread类的其他方法 推荐使用Runnable接口的方式
      In most cases, the <code>Runnable</code> interface should be used if you are only planning to override the <code>run()</code> method and no other <code>Thread</code> methods.

    • 这是很重要的 除非一个开发者想要去修改或者增强这个类的基础行为(设计层面的考量)否则一个类不应该被子类化
      This is important because classes should not be subclassed
      unless the programmer intends on modifying or enhancing the fundamental behavior of the class.


    • 核心方法:

    • run方法签名:public abstract void run();

    • 说明:

    • 当实现了Runnable接口的一个对象被用于创建一个线程时 启动这个线程将会导致这个对象的run方法在一个独立的执行线程中运行 通常run方法的契约是可以接收任何的动作

    When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.
    The general contract of the method run is that it may take any action whatsoever.

    相关文章

      网友评论

          本文标题:Concurrency: Thread类及Runnable接口的

          本文链接:https://www.haomeiwen.com/subject/pmdpzqtx.html