December 23, 2020 I was developing Android in Android Studio, and I used Thread.sleep when I wrote a program that plays music for a certain period of time and then pauses, so I will briefly summarize how to use it.
A thread is one of the execution units of processing, and refers to a series of flows from the beginning to the end of a program. There are single thread and multithread.
Single thread is also called serial processing. From the beginning to the end of the program is processed by one. Multithreading is also called concurrency. Perform two or more processes in parallel. There are four steps required to take advantage of multithreading.
The sleep method is used to pause the program. Often used in multithreading. The merit of using the sleep method is that if an infinite loop is executed with multiple threads, the load on the CPU will increase and the operation of the personal computer will become heavy. In such a case, you can use the sleep method during multithreaded processing to pause the processing to reduce the CPU load.
There are only two points to use the sleep method!
--The argument of the sleep method uses a long type, and the unit is milliseconds (1 second = 1000 milliseconds). --Always add exception handling when using the sleep method
public class Sample {
public static void main(String[] args) {
try {
//Pause for 5 seconds
Thread.sleep(5000);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public class ThreadSample {
public static void main(String[] args) {
MultiThread1 mt1 = new MultiThread1();
MultiThread2 mt2 = new MultiThread2();
mt1.start();
mt2.start();
}
}
class MultiThread1 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MultiThread2 extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Pause the program in Java, explain how to use Thread.sleep and how it works [Introduction to Java] How to stop Thread for a certain period of time with the sleep method
Recommended Posts