-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreading.java
More file actions
72 lines (59 loc) · 1.93 KB
/
MultiThreading.java
File metadata and controls
72 lines (59 loc) · 1.93 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
package com.company;
class Printer{
// synchronized void printDocuments(int numOfCopies, String docName){
void printDocuments(int numOfCopies, String docName){
for (int i=1;i<=numOfCopies;i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(">> Printing "+docName+" " + i);
}
}
}
class MyThread extends Thread{
Printer pRef;
MyThread(Printer p){
pRef = p;
}
@Override
public void run() {
synchronized (pRef) {
pRef.printDocuments(10,"SamsProfile.pdf");
}
}
}
class YourThread extends Thread{
Printer pRef;
YourThread(Printer p){
pRef = p;
}
@Override
public void run() {
synchronized (pRef) {
pRef.printDocuments(10,"TinasProfile.pdf");
}
}
}
public class MultiThreading {
//main is representing main thread
public static void main(String[] args) {
System.out.println("==Application Started==");
// I am having only 1 single object of Printer
Printer printer = new Printer();
// printer.printDocuments(10,"ChinmaysProfile.pdf");
// Scenario is that we have multiple thread working on the same printer Object
// If Multiple Threads are going to work on the same single Object we must Synchronize
MyThread mRef = new MyThread(printer); //MyThread is having reference to the Printer object
YourThread yRef = new YourThread(printer); //YourThread is having reference to the Printer object
mRef.start();
/*try {
mRef.join();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
yRef.start();
System.out.println("==Application Finished==");
}
}