logo

Thread.sleep() a Java amb exemples

La classe Java Thread proporciona les dues variants del mètode sleep(). La primera accepta només un argument, mentre que l'altra variant accepta dos arguments. El mètode sleep() s'utilitza per aturar el funcionament d'un fil durant un període de temps determinat. El temps fins al qual el fil roman en estat de repòs es coneix com a temps de repòs del fil. Un cop acabat el temps de dormir, el fil comença la seva execució des d'on ha sortit.

Sintaxi del mètode sleep():

A continuació es mostra la sintaxi del mètode sleep().

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

El mètode sleep() amb un paràmetre és el mètode natiu, i la implementació del mètode natiu es realitza en un altre llenguatge de programació. Els altres mètodes que tenen els dos paràmetres no són el mètode natiu. És a dir, la seva implementació es realitza en Java. Podem accedir als mètodes sleep() amb l'ajuda de la classe Thread, ja que la signatura dels mètodes sleep() conté la paraula clau estàtica. El mètode natiu, així com el mètode no natiu, llança una excepció marcada. Per tant, el bloc try-catch o la paraula clau throws poden funcionar aquí.

El mètode Thread.sleep() es pot utilitzar amb qualsevol fil. Significa que qualsevol altre fil o fil principal pot invocar el mètode sleep().

char en cadena java

Paràmetres:

Els següents són els paràmetres utilitzats en el mètode sleep().

mls: El temps en mil·lisegons es representa amb el paràmetre mls. La durada durant la qual el fil s'adormirà ve donada pel mètode sleep().

n: Mostra el temps addicional fins al qual el programador o desenvolupador vol que el fil estigui en estat de repòs. L'interval de n és de 0 a 999999.

forma completa iskcon

El mètode no retorna res.

Punts importants a recordar sobre el mètode Sleep().

Sempre que s'executen els mètodes Thread.sleep(), sempre atura l'execució del fil actual.

Sempre que un altre fil interromp mentre el fil actual ja està en mode de repòs, es llança l'Exception Interrupted.

convertir cadena en enumeració

Si el sistema que està executant els fils està ocupat, aleshores el temps real de repòs del fil és generalment més en comparació amb el temps passat en arguments. Tanmateix, si el sistema que executa el mètode sleep() té menys càrrega, aleshores el temps real d'inactivitat del fil és gairebé igual al temps passat a l'argument.

Exemple del mètode sleep() a Java: al fil personalitzat

L'exemple següent mostra com es pot utilitzar el mètode sleep() al fil personalitzat.

Nom de l'arxiu: TestSleepMethod1.java

jocs de missatges amb Android
 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++){>

Com bé sabeu que a la vegada només s'executa un fil. Si deixeu dormir un fil durant el temps especificat, el programador de fils agafa un altre fil i així successivament.

Exemple del mètode sleep() en Java: al fil principal

Nom de l'arxiu: 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 del mètode sleep() a Java: quan el temps de dormir és -ive

L'exemple següent presenta l'excepció IllegalArguementException quan el temps per dormir és negatiu.

Nom de l'arxiu: 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;>