Created
April 19, 2021 11:37
-
-
Save BT-ICD/d04c0ca084341dce7b5bb0ff6e6c03be to your computer and use it in GitHub Desktop.
Example of Thread Synchronization - Synchronized Method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ThreadSynchronizing; | |
/** | |
* A synchronized method, once having taken up a task, cannot be accessed by another threads until it completes the task. | |
* When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. | |
* References: | |
* https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html | |
* Programming in JAVA2 Dr. K. Somasundaram | |
* */ | |
class Printing | |
{ | |
synchronized void printNumbers(int n){ | |
System.out.println("Start"); | |
for (int i = n; i>0 ; i--) { | |
if(i==n/2){ | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(i); | |
} | |
System.out.println("End"); | |
} | |
} | |
class ThreadServe implements Runnable | |
{ | |
int n; | |
Printing pt; | |
Thread th; | |
ThreadServe(Printing pt, int x) | |
{ | |
n=x; | |
this.pt = pt; | |
th = new Thread(this); | |
th.start(); | |
} | |
@Override | |
public void run() { | |
pt.printNumbers(n); | |
} | |
} | |
class ThreadSyncDemo | |
{ | |
public static void main(String[] args) { | |
Printing p = new Printing(); | |
ThreadServe ts1 = new ThreadServe(p, 16); | |
ThreadServe ts2 = new ThreadServe(p, 8); | |
ThreadServe ts3 = new ThreadServe(p, 10); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Output
Start
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
End
Start
8
7
6
5
4
3
2
1
End
Start
10
9
8
7
6
5
4
3
2
1
End