Synchronization under concurrency control
- Eclipse: Oxygen
- Java: 1.8
Synchronization under concurrency control
Java synchronization is a concept where errors can appear in the code if the same entity is shared by two or more threads. Therefore, it can cause different results each time the execution takes place.
When we start two or more threads within a program, there may be a situation in which multiple threads try to access the same resource. Therefore, it is necessary to synchronize the action of several threads and make sure that only one thread can access the resource at a given time.
As you can see in the following program, that may or may not print a counter value in the sequence and every time it produces a different result based on the availability of the CPU for a thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class App { public static int counter = 0; public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 1000; i++) { App.counter++; } System.out.println("The loops in thread1 is over"); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 1000; i++) { App.counter++; } System.out.println("The loops in thread2 is over"); } }); thread1.start(); thread2.start(); Thread.sleep(2000); System.out.println("The value of counter is " + App.counter); } } |
Output
1 2 3 4 5 |
The loops in thread1 is over The loops in thread2 is over The value of counter is 1191 |
Contributed by: Poonam Tomar