-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPrintingDemo.java
More file actions
42 lines (35 loc) · 1.31 KB
/
Copy pathThreadPrintingDemo.java
File metadata and controls
42 lines (35 loc) · 1.31 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
36
37
38
39
40
41
42
// 1. Creating a thread by EXTENDING the Thread class
class ThreadByExtension extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Extended Thread: " + i);
// Brief pause to allow console output to mix, making concurrency visible
try { Thread.sleep(50); } catch (InterruptedException e) {}
}
}
}
// 2. Creating a thread by IMPLEMENTING the Runnable interface
class ThreadByRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Runnable Thread: " + i);
try { Thread.sleep(50); } catch (InterruptedException e) {}
}
}
}
// 3. Main Driver Class (PascalCase)
public class ThreadPrintingDemo {
public static void main(String[] args) {
System.out.println("--- Starting Threads ---");
// Instantiating the thread created via extension
ThreadByExtension thread1 = new ThreadByExtension();
// Instantiating the thread created via interface
ThreadByRunnable runnableTask = new ThreadByRunnable();
Thread thread2 = new Thread(runnableTask);
// Starting both threads concurrently
thread1.start();
thread2.start();
}
}