forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiThreading_with_sync.java
More file actions
57 lines (45 loc) · 1.03 KB
/
MultiThreading_with_sync.java
File metadata and controls
57 lines (45 loc) · 1.03 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
import java.io.*;
import java.util.*;
//https://www.geeksforgeeks.org/synchronized-in-java/
//A class to print a message
class Printer{
synchronized void printDocument(int n,String s){
for(int i=0;i<10;i++){
System.out.println("Doc is "+s+" "+i);
}
}
}
//first thread
class MyThread extends Thread{
Printer mRef;
MyThread(Printer p){
mRef=p;
}
@Override
public void run(){
mRef.printDocument(10,"MyProfile");
}
}
//second thread
class YourThread extends Thread{
Printer yRef;
YourThread(Printer p){
yRef=p;
}
@Override
public void run(){
yRef.printDocument(10,"YourProfile");
}
}
//Driver Class
class MyClass{
public static void main(String args[]){
//operation
Printer printer=new Printer();
MyThread myThread=new MyThread(printer);
YourThread yourThread=new YourThread(printer);
//start thread
myThread.start();
yourThread.start();
}
}