-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadSynchronization.java
52 lines (48 loc) · 1.08 KB
/
ThreadSynchronization.java
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
class printDemo {
public void printSequence(){
try {
for(int i = 1; i < 10;i++){
System.out.println(i+" ");
}
} catch(Exception e){
System.out.println("Thread interrupted");
}
}
}
class ThreadPrint extends Thread {
private Thread t;
private String threadName;
printDemo pd;
ThreadPrint(String t, printDemo p){
threadName = t;
pd = p;
}
public void run(){
synchronized(pd){
pd.printSequence();
System.out.println("The Thread"+threadName+" exiting");
}
}
public void start(){
System.out.println("Starting " + threadName );
if(t == null){
t = new Thread(this, threadName);
t.start();
}
}
}
public class ThreadSynchronization {
public static void main(String args[]) {
printDemo pd = new printDemo();
ThreadPrint tp1 = new ThreadPrint("T - 1", pd);
ThreadPrint tp2 = new ThreadPrint("T - 2", pd);
tp1.start();
tp2.start();
try {
tp1.join();
tp2.join();
}catch(Exception e){
System.out.println("Interrupted");
}
}
}