Java - Thread Synchronized Method

The Tutorial want to explain you a code that help you in understanding Java Method Synchronized. We have a class Synchronized Method. In order to make a method Synchronized, we add synchronized keyword to the method. The synchronized int get Count ( ) method return you the count of thread executed in a code.

The static void print(String ms) includes a Thread.currentThread ( ).get Name( ) return you the name of the current thread. The print ln print the thread Name.

Inside the main method, The run ( ) method used to create a thread, that causes the thread to be started and each thread executed separately in the application. The print ln method print the count of thread by calling from get Count ( ).

Thread threadA =new Thread(Runnable,"Thread A"): The new is used to describe that thread is created but not yet started.

Thread.start ( ): This causes the thread to start and ready for execution.

Thread.sleep ( ):This causes the currently executing thread to sleep (cease execution) as per specified number of millisecond.

On execution the code show you the count of thread and execute each thread after 500 millisecond. In case the exception exists in try block,the catch block caught and handle the exception


Here is the code:

public class SynchronizedMethod extends Object {
private static int count = 1;
public static synchronized int getCount() {
int i = count;
count++;
return i;
}
private static void print(String msg) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": " + msg);
}
public static void main(String[] args) {
try {
Runnable runnable = new Runnable() {
public void run() {
System.out.println("count=" + getCount());
}
};
Thread threadA = new Thread(runnable, "ThreadA");
threadA.start();
Thread.sleep(500);
Thread threadB = new Thread(runnable, "ThreadB");
threadB.start();
Thread.sleep(500);
Thread threadC = new Thread(runnable, "ThreadC");
threadC.start();
Thread.sleep(500);
Thread threadD = new Thread(runnable,
"ThreadD");
threadD.start();
} catch(Exception x ) {}
}
}
}

Output will be displayed as:












Related Post:-

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More