A thread is a lightweight process that can run concurrently (It means at the same time two threads are running). Each thread can handle a different task at the same time making optimized use of the available resources.
There may be a situation occurs when two threads are starting at the same time and they try to access the same resource and finally they can produce an unpredicted result due to concurrency issues.So there is a need to synchronize the multiple threads and make sure that only one thread can access the resource at a given point of time. Java programming language provides a very easy way of creating threads and synchronizing their task by using Synchronized blocks.
In this example, we have two threads which are starting at the same time and using synchronized block, a thread can be synchronized (it means when one thread completes its execution then-after other thread will start its execution).
In this example, we have two threads which are starting at the same time and using synchronized block, a thread can be synchronized (it means when one thread completes its execution then-after other thread will start its execution).
Example using Synchronization block
class Demo { public void counter() { try { for(int i = 5; i > 0; i--) { System.out.println("Count:" + i ); } }catch (Exception e) { System.out.println("Thread interrupted"); } } } class TDemo extends Thread { private Thread t; Demo obj1; ThreadDemo(Demo obj) { obj1 = obj; } public void run() { synchronized(obj1){ obj1.counter(); } } public void start() { if (t == null) { t = new Thread(); t.start(); } } } public class Test { public static void main(String args[]) { Demo obj2 = new Demo(); ThreadDemo T1 = new ThreadDemo(obj2); ThreadDemo T2 = new ThreadDemo(obj2); T1.start(); T2.start(); try { T1.join(); T2.join(); }catch( Exception e) { System.out.println("Interrupted"); } } }
Output
count:5
count:4
count:3
count:2
count:1
count:5
count:4
count:3
count:2
count:1
Example without using Synchronization block
class Demo { public void counter() { try { for(int i = 5; i > 0; i--) { System.out.println("Count:" + i ); } }catch (Exception e) { System.out.println("Thread interrupted"); } } } class TDemo extends Thread { private Thread t; Demo obj1; ThreadDemo(Demo obj) { obj1 = obj; } public void run() { obj1.counter(); } public void start() { if (t == null) { t = new Thread(); t.start(); } } } public class Test { public static void main(String args[]) { Demo obj2 = new Demo(); ThreadDemo T1 = new ThreadDemo(obj2); ThreadDemo T2 = new ThreadDemo(obj2); T1.start(); T2.start(); try { T1.join(); T2.join(); }catch( Exception e) { System.out.println("Interrupted"); } } }
Output
count:5
count:4
count:3
count:5
count:2
count:4
count:1
count:3
count:2
count:1
No comments:
Post a Comment