logo

Mètode Java Thread start().

El començar() El mètode de la classe del fil s'utilitza per començar l'execució del fil. El resultat d'aquest mètode són dos fils que s'executen simultàniament: el fil actual (que torna de la trucada al mètode d'inici) i l'altre fil (que executa el seu mètode d'execució).

El mètode start() crida internament al mètode run() de la interfície Runnable per executar el codi especificat al mètode run() en un fil separat.

El fil inicial realitza les tasques següents:

  • Indica un fil nou
  • El fil passa d'estat nou a estat executable.
  • Quan el fil tingui l'oportunitat d'executar-se, s'executarà el seu mètode run() target.

Sintaxi

 public void start() 

Valor de retorn

 It does not return any value. 

Excepció

IllegalThreadStateException - Aquesta excepció es produeix si el mètode start() es crida més d'una vegada.

Exemple 1: ampliant la classe de fil

 public class StartExp1 extends Thread { public void run() { System.out.println('Thread is running...'); } public static void main(String args[]) { StartExp1 t1=new StartExp1(); // this will call run() method t1.start(); } } 
Prova-ho ara

Sortida:

 Thread is running... 

Exemple 2: mitjançant la implementació d'una interfície executable

 public class StartExp2 implements Runnable { public void run() { System.out.println('Thread is running...'); } public static void main(String args[]) { StartExp2 m1=new StartExp2 (); Thread t1 =new Thread(m1); // this will call run() method t1.start(); } } 
Prova-ho ara

Sortida:

 Thread is running... 

Exemple 3: quan crideu al mètode start() més d'una vegada

 public class StartExp3 extends Thread { public void run() { System.out.println('First thread running...'); } public static void main(String args[]) { StartExp3 t1=new StartExp3(); t1.start(); // It will through an exception because you are calling start() method more than one time t1.start(); } } 
Prova-ho ara

Sortida:

 First thread running... Exception in thread 'main' java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:708) at StartExp3.main(StartExp3.java:12)