synchronized blocks the next thread's call to method
as long as the previous thread's execution is not finished.
Threads can access this method one at a time.
Without synchronized all threads can access this method simultaneously.
public class MyCounter {
private int count = 0;
public synchronized void add(int value){
this.count += value;
}
}
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
// Example illustrates multiple threads are executing
// on the same Object at same time without synchronization.
import java.io.*;
class Line
{
// if multiple threads(trains) will try to
// access this unsynchronized method,
// they all will get it. So there is chance
// that Object's state will be corrupted.
public void getLine()
{
for (int i = 0; i < 3; i++)
{
System.out.println(i);
try
{
Thread.sleep(400);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
class Train extends Thread
{
// reference to Line's Object.
Line line;
Train(Line line)
{
this.line = line;
}
@Override
public void run()
{
line.getLine();
}
}
class GFG
{
public static void main(String[] args)
{
// Object of Line class that is shared
// among the threads.
Line obj = new Line();
// creating the threads that are
// sharing the same Object.
Train train1 = new Train(obj);
Train train2 = new Train(obj);
// threads start their execution.
train1.start();
train2.start();
}
}
class Table
{
void printTable(int n){
synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}