Java Synchronization

Java Synchronization


Posted in : Java Posted on : April 19, 2012 at 6:33 PM Comments : [ 0 ]

In this tutorial you will learn about synchronization in Java

Java Synchronization

Synchronization is a process of sharing common resources among multiple threads so that only one thread can access that resource at a time. The resources may be printer, a file, database connection etc. In java we use synchronized key word to achieve synchronization. We create synchronized methods or synchronized blocks to block the and the those code which needs to be thread safe.

An Example of Synchronization is given below

Resource.java

package net.roseindia.synchronization;

public class Resource {
	void call(String string) {
		System.out.println(string);
		try {
			/* Paused for 2 Second */
			Thread.sleep(2 * 1000);
		} catch (Exception e) {
			System.out.println("Interrupted During Execution");
			e.printStackTrace();
		}
	}
}

ResourceUser.java

package net.roseindia.synchronization;

public class ResourceUser implements Runnable {
	String message;
	Resource resource;
	Thread thread;

	public ResourceUser(Resource resource, String string) {
		this.resource = resource;
		this.message = string;
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		synchronized (resource) {
			resource.call(message);
		}
	}
}

MainClaz.java

package net.roseindia.synchronization;

public class MainClaz {
	public static void main(String args[]) {
		Resource resource = new Resource();

		ResourceUser resourceUser = new ResourceUser(resource,
				"Going to Synchronize");
		ResourceUser resourceUser1 = new ResourceUser(resource, "Synchronized");
		ResourceUser resourceUser2 = new ResourceUser(resource, "End");

		try {
			resourceUser.thread.join();
			resourceUser1.thread.join();
			resourceUser2.thread.join();
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}


When you run this application it will display message as shown below:


Going to Synchronize
Synchronized
End

Download Select Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics