logo

Interfície executable de Java

java.lang.Runnable és una interfície que ha de ser implementada per una classe les instàncies de la qual estan destinades a ser executades per un fil. Hi ha dues maneres d'iniciar un nou Thread: Subclass Thread i implementar Runnable. No cal subclassificar un fil quan es pot fer una tasca anul·lant només el córrer () mètode de Runnable. 

Passos per crear un fil nou amb Runnable 

  1. Creeu un implementador Runnable i implementeu el mètode run(). 
  2. Crea una instancia de la classe Thread i passa l'implementador al Thread Thread té un constructor que accepta instàncies executables.
  3. Invocar start() de l'inici de la instància Thread internament crida a run() de l'implementador.
    • Invocant start() es crea un nou fil que executa el codi escrit a run().
    • Cridar a run() directament no crea ni inicia un fil nou, s'executarà al mateix fil.
    • Per iniciar una nova línia d'execució, crida a start() al fil. 

Exemple:

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();  } } 

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

Explicació: La sortida mostra dos fils actius al programa: el fil principal i el mètode principal Thread-0 l'executa el fil principal, però invocant l'inici a RunnableImpl es crea i s'inicia un fil nou: Thread-0.



matriu afegint elements java

Gestió de l'excepció a Runnable

La interfície executable no pot llançar excepcions marcades, però RuntimeException es pot llançar des de run(). Les excepcions no detectades les gestiona el controlador d'excepcions del fil si la JVM no pot gestionar o capturar excepcions, imprimeix la traça de la pila i finalitza el flux. 

Exemple:

llista de religions
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();  } } 

Sortida:

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ó : La sortida mostra que Runnable no pot llançar excepcions marcades FileNotFoundException en aquest cas, per als trucadors, ha de gestionar les excepcions marcades a l'execució (), però les excepcions d'execució (llençades o generades automàticament) les gestiona la JVM automàticament.

Crea un qüestionari