Java - Thread Synchronization
Java - Thread Synchronization | Javamazon:
'via Blog this'
'via Blog this'
thread synchronization in java
Before We have discussed about :
Now will discuss small Demo on thread synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization.
The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object’s lock.
This is the general form of the synchronized statement:
synchronized(object) { // statements to be synchronized }
Here is an example, using a synchronized block within the run( ) method:
// File Name : SyncMe.java // This program uses a synchronized block. class SyncMe { void Meth(String msg) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Interrupted"); } System.out.println("]"); } } // File Name : Synced.java class Synced implements Runnable { String msg; SyncMe target; Thread t; public Synced(SyncMe targ, String s) { target = targ; msg = s; t = new Thread(this); t.start(); } // synchronize here public void run() { synchronized(target) { // synchronized block target.Meth(msg); } } } // File Name : Synch.java class Synch { public static void main(String args[]) { SyncMe target = new SyncMe(); Synced obj1 = new Synced(target, "Hello"); Synced obj2 = new Synced(target, "Synchronized"); Synced obj3 = new Synced(target, "World"); // wait for threads to end try { obj1.t.join(); obj2.t.join(); obj3.t.join(); } catch(InterruptedException e) { System.out.println("Interrupted"); } } }
For Users familar with threads they can have a quick look on Multi Threading/Tasking Interview Questions
0 comments:
Post a Comment