-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunnableThreadExample.java
More file actions
35 lines (29 loc) · 1.39 KB
/
Copy pathRunnableThreadExample.java
File metadata and controls
35 lines (29 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class RunnableThreadExample implements Runnable {
// The run method contains the code that will be executed by the thread
@Override
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + Thread.currentThread().getName() + " is running.");
// Suspend the thread for 500 milliseconds
Thread.sleep(500);
}
} catch (InterruptedException e) {
// Handle the exception if the sleeping thread is interrupted
System.out.println("Thread: " + Thread.currentThread().getName() + " was interrupted.");
}
}
public static void main(String[] args) {
System.out.println("--- Starting Thread Demonstration ---");
// 1. Create instances of the class implementing Runnable
RunnableThreadExample task1 = new RunnableThreadExample();
RunnableThreadExample task2 = new RunnableThreadExample();
// 2. Create Thread objects and pass the Runnable instances to their constructors
// We also give them meaningful names ("Thread-1" and "Thread-2")
Thread t1 = new Thread(task1, "Thread-1");
Thread t2 = new Thread(task2, "Thread-2");
// 3. Start the threads (This triggers the run() method in separate call stacks)
t1.start();
t2.start();
}
}