-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadClass.java
More file actions
98 lines (85 loc) · 2.21 KB
/
Copy pathThreadClass.java
File metadata and controls
98 lines (85 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package codingInterview.thread;
//Java program to demonstrate thread states
class thread implements Runnable
{//states : NEW,Runnable, Waiting, blocked,timewaiting, terminated
public void run()
{
// moving thread2 to timed waiting state
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread1 while it called join() method on thread2 -"+
ThreadClass.thread1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ThreadClass implements Runnable
{
public static Thread thread1;
public static ThreadClass obj;
public static void main(String[] args)
{
obj = new ThreadClass();
thread1 = new Thread(obj);
// thread1 created and is currently in the NEW state.
System.out.println("State of thread1 after creating it - " + thread1.getState());
thread1.start();
// thread1 moved to Runnable state
System.out.println("State of thread1 after calling .start() method on it - " +
thread1.getState());
}
public void run()
{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);
// thread1 created and is currently in the NEW state.
System.out.println("State of thread2 after creating it - "+ thread2.getState());
thread2.start();
// thread2 moved to Runnable state
System.out.println("State of thread2 after calling .start() method on it - " +
thread2.getState());
// moving thread1 to timed waiting state
try
{
//moving thread2 to timed waiting state
Thread.sleep(200);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 after calling .sleep() method on it - "+
thread2.getState() );
try
{
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's execution - " +
thread2.getState());
}
}