logo

Interfaz ejecutable de Java

java.lang.Runnable es una interfaz que será implementada por una clase cuyas instancias están destinadas a ser ejecutadas por un hilo. Hay dos formas de iniciar un nuevo subproceso: subclase de subproceso e implementar Runnable. No es necesario subclasificar un subproceso cuando una tarea se puede realizar anulando sólo el correr() método de ejecutable. 

Pasos para crear un nuevo hilo usando Runnable 

  1. Cree un implementador Runnable e implemente el método run(). 
  2. Cree una instancia de la clase Thread y pase el implementador al Thread. Thread tiene un constructor que acepta instancias Runnable.
  3. Invocar start() de la instancia de Thread start llama internamente a run() del implementador.
    • Invocar start() crea un nuevo hilo que ejecuta el código escrito en run().
    • Llamar a run() directamente no crea ni inicia un nuevo subproceso, se ejecutará en el mismo subproceso.
    • Para iniciar una nueva línea de ejecución, llame a start() en el hilo. 

Ejemplo:

java
// Runnable Interface Implementation public class Geeks  {  private class RunnableImpl implements Runnable   {  // Overriding the run Method  @Override  public void run()  {  System.out.println(Thread.currentThread().getName()  + ' executing run() method!');  }  }     // Main Method  public static void main(String[] args)   {   System.out.println('Main thread is: '  + Thread.currentThread().getName());    // Creating Thread  Thread t1 = new Thread(new Geeks().new RunnableImpl());    // Executing the Thread  t1.start();  } } 

Producción
Main thread is: main Thread-0 executing run() method! 

Explicación: El resultado muestra dos subprocesos activos en el programa: el subproceso principal y el método principal Thread-0 es ejecutado por el subproceso principal, pero al invocar el inicio en RunnableImpl se crea e inicia un nuevo subproceso: Thread-0.



diagrama de clases de java

Manejo de excepciones en Runnable

La interfaz ejecutable no puede generar una excepción marcada, pero RuntimeException se puede generar desde run(). Las excepciones no detectadas son manejadas por el controlador de excepciones del subproceso. Si JVM no puede manejar o detectar excepciones, imprime el seguimiento de la pila y finaliza el flujo. 

Ejemplo:

cómo emparejar auriculares beats
java
// Checking Exceptions in Runnable Interface import java.io.FileNotFoundException; public class Geeks {  private class RunnableImpl implements Runnable   {  // Overriding the run method   @Override  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();  }  }    public static void main(String[] args)  {  System.out.println('Main thread is: ' +  Thread.currentThread().getName());     // Create a Thread  Thread t1 = new Thread(new Geeks().new RunnableImpl());    // Running the Thread  t1.start();  } } 

Producción:

Thread-0 executing run() method!  
Must catch here!
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)

Explicación : El resultado muestra que Runnable no puede generar excepciones marcadas. Excepción de archivo no encontrado en este caso, para las personas que llaman, debe manejar las excepciones marcadas en run(), pero la JVM maneja automáticamente las RuntimeExceptions (lanzadas o generadas automáticamente).

Crear cuestionario