logo

Thread.sleep() in Java con esempi

La classe Java Thread fornisce le due varianti del metodo sleep(). La prima accetta solo un argomento, mentre l'altra variante accetta due argomenti. Il metodo sleep() viene utilizzato per interrompere il funzionamento di un thread per un determinato periodo di tempo. Il tempo durante il quale il thread rimane nello stato di sonno è noto come tempo di sonno del thread. Al termine del tempo di sospensione, il thread inizia la sua esecuzione da dove si era interrotto.

La sintassi del metodo sleep():

Di seguito è riportata la sintassi del metodo sleep().

 public static void sleep(long mls) throws InterruptedException public static void sleep(long mls, int n) throws InterruptedException 

Il metodo sleep() con un parametro è il metodo nativo e l'implementazione del metodo nativo viene eseguita in un altro linguaggio di programmazione. Gli altri metodi con i due parametri non sono il metodo nativo. Cioè, la sua implementazione è realizzata in Java. Possiamo accedere ai metodi sleep() con l'aiuto della classe Thread, poiché la firma dei metodi sleep() contiene la parola chiave static. Il metodo nativo, così come quello non nativo, lancia un'eccezione controllata. Pertanto, in questo caso possono funzionare sia il blocco try-catch che la parola chiave Throws.

Il metodo Thread.sleep() può essere utilizzato con qualsiasi thread. Significa che qualsiasi altro thread o il thread principale può invocare il metodo sleep().

parametri:

Di seguito sono riportati i parametri utilizzati nel metodo sleep().

ml: Il tempo in millisecondi è rappresentato dal parametro mls. La durata per la quale il thread resterà dormiente è data dal metodo sleep().

N: Mostra il tempo aggiuntivo fino al quale il programmatore o lo sviluppatore desidera che il thread sia in stato di sospensione. L'intervallo di n è compreso tra 0 e 999999.

Il metodo non restituisce nulla.

Punti importanti da ricordare sul metodo Sleep()

Ogni volta che i metodi Thread.sleep() vengono eseguiti, interrompe sempre l'esecuzione del thread corrente.

Ogni volta che un altro thread esegue un'interruzione mentre il thread corrente è già in modalità di sospensione, viene lanciata l'InterruptedException.

Se il sistema che sta eseguendo i thread è occupato, il tempo di sospensione effettivo del thread è generalmente maggiore rispetto al tempo trascorso negli argomenti. Tuttavia, se il sistema che esegue il metodo sleep() ha un carico inferiore, il tempo di sospensione effettivo del thread è quasi uguale al tempo trascorso nell'argomento.

Esempio del metodo sleep() in Java: sul thread personalizzato

L'esempio seguente mostra come utilizzare il metodo sleep() sul thread personalizzato.

Nome del file: TestSleepMethod1.java

 class TestSleepMethod1 extends Thread{ public void run(){ for(int i=1;i<5;i++){ 500 the thread will sleep for milli seconds try{thread.sleep(500);}catch(interruptedexception e){system.out.println(e);} system.out.println(i); } public static void main(string args[]){ testsleepmethod1 t1="new" testsleepmethod1(); t2="new" t1.start(); t2.start(); < pre> <p> <strong>Output:</strong> </p> <pre> 1 1 2 2 3 3 4 4 </pre> <p>As you know well that at a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up another thread and so on.</p> <h3>Example of the sleep() Method in Java : on the main thread</h3> <p> <strong>FileName:</strong> TestSleepMethod2.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable's value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;></pre></5;i++){>

Come sai bene che alla volta viene eseguito un solo thread. Se sospendi un thread per il tempo specificato, lo scheduler dei thread ne prenderà un altro e così via.

Esempio del metodo sleep() in Java: sul thread principale

Nome del file: TestSleepMethod2.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;>

Esempio del metodo sleep() in Java: quando il tempo di sonno è -ive

L'esempio seguente genera l'eccezione IllegalArguementException quando il tempo per la sospensione è negativo.

Nome del file: TestSleepMethod3.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;>