java.lang.Runnable è un'interfaccia che deve essere implementata da una classe le cui istanze devono essere eseguite da un thread. Esistono due modi per avviare un nuovo thread: thread sottoclasse e implementare Runnable. Non è necessario creare una sottoclasse di un Thread quando un'attività può essere eseguita sovrascrivendo solo il file correre() metodo di Runnable.
Passaggi per creare un nuovo thread utilizzando Runnable
- Crea un implementatore Runnable e implementa il metodo run().
- Crea un'istanza della classe Thread e passa l'implementatore al Thread Thread ha un costruttore che accetta istanze eseguibili.
- Richiama start() dell'istanza Thread start chiama internamente run() dell'implementatore.
- L'invocazione di start() crea un nuovo thread che esegue il codice scritto in run().
- La chiamata diretta a run() non crea e avvia un nuovo thread, verrà eseguito nello stesso thread.
- Per iniziare una nuova riga di esecuzione, chiama start() sul thread.
Esempio:
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(); } }
Produzione
Main thread is: main Thread-0 executing run() method!
Spiegazione: L'output mostra due thread attivi nel programma: thread principale e Thread-0. Il metodo principale viene eseguito dal thread Main ma invocando l'avvio su RunnableImpl crea e avvia un nuovo thread: Thread-0.
stringa della data java
Gestione delle eccezioni in Runnable
L'interfaccia eseguibile non può lanciare un'eccezione controllata ma RuntimeException può essere lanciata da run(). Le eccezioni non rilevate vengono gestite dal gestore eccezioni del thread. Se JVM non è in grado di gestire o rilevare eccezioni, stampa la traccia dello stack e termina il flusso.
Esempio:
stringa javajava
// 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(); } }
Produzione:
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)
Spiegazione : L'output mostra che Runnable non può generare eccezioni controllate FileNotFoundException in questo caso i chiamanti devono gestire le eccezioni verificate in run() ma le RuntimeException (generate o generate automaticamente) vengono gestite automaticamente dalla JVM.
Crea quiz