forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNamePrint.java
71 lines (63 loc) · 2.11 KB
/
NamePrint.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.rampatra.threads;
/**
* Problem Description: Print first name and last name (in order) using two different threads 1000 times.
*
* @author rampatra
* @since 10/6/15
*/
public class NamePrint {
Object lock = new Object();
volatile boolean isFirstNamePrinted = false;
class PrintFirstName implements Runnable {
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < 1000; i++) {
try {
// wait if first name is printed but not the last name
if (isFirstNamePrinted) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("Ram ");
isFirstNamePrinted = true;
lock.notify();
}
}
}
}
class PrintLastName implements Runnable {
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < 1000; i++) {
try {
// wait if first name is not printed
if (!isFirstNamePrinted) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Swaroop");
isFirstNamePrinted = false;
lock.notify();
}
}
}
}
public void printNameUsingMultipleThreads() {
Runnable printFirstName = new PrintFirstName();
Runnable printLastName = new PrintLastName();
Thread firstThread = new Thread(printFirstName);
Thread secondThread = new Thread(printLastName);
firstThread.start();
secondThread.start();
}
public static void main(String[] args) {
NamePrint obj = new NamePrint();
obj.printNameUsingMultipleThreads();
}
}