-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunThreads.java
More file actions
69 lines (45 loc) · 1.87 KB
/
RunThreads.java
File metadata and controls
69 lines (45 loc) · 1.87 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
import java.util.*;
public class RunThreads {
final static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws InterruptedException{
String firstThreadName, secondThreadName;
System.out.print("Enter first thread name: ");
firstThreadName = input.nextLine();
do {
System.out.print("Enter second thread name: ");
secondThreadName = input.nextLine();
if(firstThreadName.equals(secondThreadName)) {
System.out.println("Enter a unique thread name.");
}
}while(secondThreadName.equals(firstThreadName));
Thread firstThread = new Thread(new HandleThreads(firstThreadName));
Thread secondThread = new Thread(new HandleThreads(secondThreadName));
System.out.println(firstThreadName + " is: "+firstThread.getState());
System.out.println(secondThreadName + " is: "+secondThread.getState());
// start your thread.
System.out.println("Thread is starting...");
firstThread.start();
secondThread.start();
// terminate the thread.
firstThread.join();
secondThread.join();
System.out.println("After sleep...");
Thread.sleep(2000); // add 2 seconds delay
System.out.println(firstThreadName + " is: "+firstThread.getState());
System.out.println(secondThreadName + " is: "+secondThread.getState());
}
}
class HandleThreads extends Thread {
private String threadName;
public HandleThreads(String threadName) {
this.threadName = threadName;
}
public void run() {
try {
Thread.sleep(2000); // add 2 seconds delay
System.out.println(threadName + " is: "+Thread.currentThread().getState());
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}