How to Perform an Action Periodically Using Thread in Java?
Share
Condition for Performing an Action Periodically Using Thread in Java
Description:
To perform an action periodically in Java, a thread can be used with the `Thread.sleep()` method inside a loop to introduce delays between actions. This method pauses the thread for a specified time before executing the action again. Alternatively, `ScheduledExecutorService` offers a more efficient and flexible approach for scheduling periodic tasks. Proper exception handling and thread management are essential for ensuring smooth execution.
Sample Source Code
# PeriodicAction1.java
package JavaSamples;
import javax.swing.JOptionPane;
public class PeriodicAction1 extends javax.swing.JFrame {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
STEP 1: The user creates the GUI to perform the thread operation.
STEP 2: After clicking the 'Periodic Action' button, a new thread is started to perform an action (appending a message to the JTextArea) every 2 seconds for a maximum duration of 10 seconds.
STEP 3: Once the time limit is reached, a dialog box displays the total number of actions performed.