logo

Thread.sleep() en Java avec des exemples

La classe Java Thread fournit les deux variantes de la méthode sleep(). La première n’accepte qu’un argument, tandis que l’autre variante accepte deux arguments. La méthode sleep() est utilisée pour arrêter le fonctionnement d'un thread pendant une durée donnée. Le temps pendant lequel le thread reste en état de veille est appelé temps de veille du thread. Une fois le temps de veille terminé, le thread démarre son exécution là où il s'est arrêté.

Syntaxe de la méthode sleep() :

Voici la syntaxe de la méthode sleep().

alphabet sous forme de chiffres
 public static void sleep(long mls) throws InterruptedException public static void sleep(long mls, int n) throws InterruptedException 

La méthode sleep() avec le seul paramètre est la méthode native, et l'implémentation de la méthode native est réalisée dans un autre langage de programmation. Les autres méthodes ayant les deux paramètres ne sont pas la méthode native. Autrement dit, son implémentation est réalisée en Java. Nous pouvons accéder aux méthodes sleep() à l'aide de la classe Thread, car la signature des méthodes sleep() contient le mot-clé static. La méthode native, ainsi que la méthode non native, lèvent une exception vérifiée. Par conséquent, soit le bloc try-catch, soit le mot-clé throws peuvent fonctionner ici.

La méthode Thread.sleep() peut être utilisée avec n’importe quel thread. Cela signifie que n'importe quel autre thread ou le thread principal peut invoquer la méthode sleep().

Paramètres:

Voici les paramètres utilisés dans la méthode sleep().

ml : Le temps en millisecondes est représenté par le paramètre mls. La durée pendant laquelle le thread va dormir est donnée par la méthode sleep().

n: Il indique le temps supplémentaire pendant lequel le programmeur ou le développeur souhaite que le thread soit en état de veille. La plage de n va de 0 à 999999.

La méthode ne renvoie rien.

Points importants à retenir concernant la méthode Sleep()

Chaque fois que les méthodes Thread.sleep() s'exécutent, elles arrêtent toujours l'exécution du thread en cours.

java pour les types de boucles

Chaque fois qu'un autre thread s'interrompt alors que le thread actuel est déjà en mode veille, l'InterruptedException est levée.

Si le système qui exécute les threads est occupé, le temps de veille réel du thread est généralement supérieur au temps passé dans les arguments. Cependant, si le système exécutant la méthode sleep() a moins de charge, alors le temps de veille réel du thread est presque égal au temps passé dans l'argument.

Exemple de la méthode sleep() en Java : sur le thread personnalisé

L'exemple suivant montre comment utiliser la méthode sleep() sur le thread personnalisé.

Nom de fichier: 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++){>

Comme vous le savez bien, un seul thread est exécuté à la fois. Si vous mettez un thread en veille pendant la durée spécifiée, le planificateur de thread prend un autre thread et ainsi de suite.

Exemple de la méthode sleep() en Java : sur le thread principal

Nom de fichier: 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;>

Exemple de la méthode sleep() en Java : lorsque le temps de sommeil est -ive

L'exemple suivant lève l'exception IllegalArguementException lorsque le temps de mise en veille est négatif.

Nom de fichier: 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;>