-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreads.java
More file actions
72 lines (60 loc) · 2.21 KB
/
MultiThreads.java
File metadata and controls
72 lines (60 loc) · 2.21 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class MultiThreads {
public static void main(String[] args) {
System.out.println("Multi-Threading Example");
System.out.println("----------------------");
// Create and start CSthread
Thread csThread = new Thread(new CSThread());
csThread.setName("CSthread");
csThread.start();
// Create and start ITthread
Thread itThread = new Thread(new ITThread());
itThread.setName("ITthread");
itThread.start();
// Wait for threads to complete
try {
csThread.join();
itThread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
// CSThread implementation
class CSThread implements Runnable {
private int executionCount = 0;
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
executionCount++;
System.out.println(Thread.currentThread().getName() +
" executing, count: " + executionCount);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
}
// ITThread implementation
class ITThread implements Runnable {
private int executionCount = 0;
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
executionCount++;
System.out.println(Thread.currentThread().getName() +
" executing, count: " + executionCount);
// Sleep for 500 milliseconds
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " interrupted.");
}
System.out.println(Thread.currentThread().getName() + " exiting.");
}
}