📜  Java中的可运行接口

📅  最后修改于: 2022-05-13 01:55:24.502000             🧑  作者: Mango

Java中的可运行接口

java.lang.Runnable是一个由类实现的接口,该类的实例旨在由线程执行。有两种方法可以启动一个新线程——子类Thread和实现Runnable 。当可以通过仅覆盖Runnablerun()方法来完成任务时,不需要子类化Thread

使用Runnable创建新Thread的步骤:
1 、创建一个Runnable实现器,实现run()方法。
2.实例化Thread类并将实现者传递给ThreadThread有一个接受Runnable实例的构造函数。
3.调用Thread实例的start() ,start内部调用implementer的run() 。调用start() ,创建一个执行run()中编写的代码的新Thread
直接调用run()不会创建和启动新的Thread ,它将在同一个线程中运行。要开始新的执行行,请在线程上调用start()
例子,

public class RunnableDemo {
  
    public static void main(String[] args)
    {
        System.out.println("Main thread is- "
                        + Thread.currentThread().getName());
        Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());
        t1.start();
    }
  
    private class RunnableImpl implements Runnable {
  
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                             + ", executing run() method!");
        }
    }
}

输出:

Main thread is- main
Thread-0, executing run() method!

输出显示程序中有两个活动线程——主线程和 Thread-0,main 方法由主线程执行,但在RunnableImpl上调用 start 会创建并启动一个新线程——Thread-0。

当 Runnable 遇到异常时会发生什么?
Runnable不能抛出检查异常,但RuntimeException可以从run()抛出。未捕获的异常由线程的异常处理程序处理,如果 JVM 无法处理或捕获异常,它会打印堆栈跟踪并终止流程。
例子,

import java.io.FileNotFoundException;
  
public class RunnableDemo {
  
    public static void main(String[] args)
    {
        System.out.println("Main thread is- " +
                          Thread.currentThread().getName());
        Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());
        t1.start();
    }
  
    private class RunnableImpl implements Runnable {
  
        public void run()
        {
            System.out.println(Thread.currentThread().getName()
                             + ", executing run() method!");
            /**
             * Checked exception can't be thrown, Runnable must
             * handle checked exception itself.
             */
            try {
                throw new FileNotFoundException();
            }
            catch (FileNotFoundException e) {
                System.out.println("Must catch here!");
                e.printStackTrace();
            }
  
            int r = 1 / 0;
            /*
             * Below commented line is an example
             * of thrown RuntimeException.
             */
            // throw new NullPointerException();
        }
    }
}

输出:

java.io.FileNotFoundException
    at RunnableDemo$RunnableImpl.run(RunnableDemo.java:25)
    at java.lang.Thread.run(Thread.java:745)
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
    at RunnableDemo$RunnableImpl.run(RunnableDemo.java:31)
    at java.lang.Thread.run(Thread.java:745)

输出显示Runnable不能向调用者抛出已检查的异常,在这种情况下为FileNotFoundException ,它必须在run()中处理已检查的异常,但 RuntimeExceptions(抛出或自动生成)由 JVM 自动处理。

参考 :
http://www.javargon.com/2016/11/javalangrunnable-interface.html