logo

Interface executável Java

java.lang.Runnable é uma interface que deve ser implementada por uma classe cujas instâncias devem ser executadas por um thread. Existem duas maneiras de iniciar um novo Thread - Subclass Thread e implementar Runnable. Não há necessidade de subclassificar um Thread quando uma tarefa pode ser executada substituindo apenas o correr() método de executável. 

Etapas para criar um novo thread usando Runnable 

  1. Crie um implementador Runnable e implemente o método run(). 
  2. Instancie a classe Thread e passe o implementador para o Thread Thread possui um construtor que aceita instâncias Runnable.
  3. Invoque start() da instância Thread start chama internamente run() do implementador.
    • Invocar start() cria um novo Thread que executa o código escrito em run().
    • Chamar run() diretamente não cria e inicia um novo Thread, ele será executado no mesmo thread.
    • Para iniciar uma nova linha de execução, chame start() no thread. 

Exemplo:

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

Saída
Main thread is: main Thread-0 executing run() method! 

Explicação: A saída mostra dois threads ativos no programa - thread principal e Thread-0 O método principal é executado pelo thread principal, mas invocar o início em RunnableImpl cria e inicia um novo thread - Thread-0.



derivadas parciais em látex

Tratamento de exceção em executável

A interface executável não pode lançar exceção verificada, mas RuntimeException pode ser lançada a partir de run(). Exceções não detectadas são tratadas pelo manipulador de exceções do encadeamento. Se a JVM não puder tratar ou capturar exceções, ela imprimirá o rastreamento de pilha e encerrará o fluxo. 

Exemplo:

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

Saída:

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)

Explicação : A saída mostra que Runnable não pode lançar exceções verificadas FileNotFoundException neste caso, para os chamadores, ele deve tratar exceções verificadas em run() mas RuntimeExceptions (lançadas ou geradas automaticamente) são tratadas automaticamente pela JVM.

Criar questionário