-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronizedMethodDemo.java
More file actions
52 lines (51 loc) · 1.1 KB
/
SynchronizedMethodDemo.java
File metadata and controls
52 lines (51 loc) · 1.1 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
class Callme{
void call(String msg){
//synchronized void call(String msg){ //Here i'm creating a synchronized shared method
System.out.print("[" + msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Call me interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable{
String msg;
Callme target;
Thread t;
public Caller(Callme targ,String s){
target = targ;
msg = s;
t = new Thread(this);
t.start();
// System.out.println(t);
}
public void run(){
target.call(msg);
/*
* Here i'm creating synchronized target;
*
synchronized(target){
target.call(msg);
}
/
*/
}
}
public class SynchronizedMethodDemo {
public static void main(String args[]){
Callme target = new Callme();
Caller obj1 = new Caller(target,"Hello");
Caller obj2 = new Caller(target,"Synchronized");
Caller obj3 = new Caller(target,"World");
try{
obj1.t.join();
obj2.t.join();
obj3.t.join();
}catch(InterruptedException e){
System.out.println("Main thread interrupted");
}
System.out.println("Main thread exited normally");
}
}