The thread is a lightweight sub process. It does not require a dedicated resource. It runs inside the process so its shares and utilize resources which is already allocated to the process. If you are running the more than one thread concurrently its call multithreading. If we are playing in multiple threads with the shared resources there is chances to face the concurrency issue, So we should handle it.
Thread Sample Code
In below example I want to print the value 1,2,3 but its printed values inconsistently
package com.samplecoder.threading;
public class MultiThreading {
private static int count = 0;
private static void increaseCount() {
count += 1;
System.out.println("Running :"+ Thread.currentThread().getName() +" And Count is : "+count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(() -> {
increaseCount();
}, "Thread 1");
Thread t2 = new Thread(() -> {
increaseCount();
}, "Thread 2");
Thread t3 = new Thread(() -> {
increaseCount();
}, "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
Result
Running :Thread 1 And Count is : 2
Running :Thread 2 And Count is : 2
Running :Thread 3 And Count is : 3
Synchronization
To avoid consistency issue the best way is making method or necessary blocks to synchronized. Here I will make increaseCount method as synchronized to get the result as I expected.
package com.samplecoder.threading;
public class MultiThreading {
private static int count = 0;
private static synchronized void increaseCount() {
count += 1;
System.out.println("Running :"+ Thread.currentThread().getName() +" And Count is : "+count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(() -> {
increaseCount();
}, "Thread 1");
Thread t2 = new Thread(() -> {
increaseCount();
}, "Thread 2");
Thread t3 = new Thread(() -> {
increaseCount();
}, "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
Result
Running :Thread 1 And Count is : 1
Running :Thread 3 And Count is : 2
Running :Thread 2 And Count is : 3