Thread synchronization in java

              This is another type of synchronization which deals with thread. Once the threads are created, it has to be coordinated and mange multithreading.

The types of thread synchronization are given below.

·       Inter thread communication

·       Mutual exclusive

It can be achieved by following ways.

Each and all types are explained as follows.

Atomic classes:

              Atomic means unique. Atomic classes use single variables to process the thread. The process includes the increment,decrement and compare the value. It makes the thread to be safe in all times.

Program:

  • This program starts with including the java package java.util.concurrent.atomic.AtomicInteger.
  • Two classes are created. One is the method definitions and another one is main() class.
  • First class is “CountIt”. It includes a atomic value ‘c1’. Function a_incre() is used to increment the value. Next one is “getTheCount()” which is used to find the counted value.
  • AtomicSample is the main() class. It is used to create the objects and call the functions to print the value.

Code:

import java.util.concurrent.atomic.AtomicInteger;

class CountIt {

    private AtomicInteger c1 = new AtomicInteger(0);

    public void a_incre() {

        c1.incrementAndGet(); // it increments the value.

    }

    public int getTheCount() {

        return c1.get();

    }

}

public class AtomicSample{

    public static void main(String[] args) throws InterruptedException {

        CountIt c1 = new CountIt();

        Thread t1 = new Thread(() -> {

            for (int i = 0; i < 100; i++) c1.a_incre();

        });

        Thread t2 = new Thread(() -> {

            for (int i = 0; i < 540; i++) c1.a_incre();

        });

        t1.start();

        t2.start();

        t1.join();

        t2.join();

        System.out.println("The Final Count is: " + c1.getTheCount());

    }

}

Output:

Compile the java program and get the class file.

C:\raji\blog>javac AtomicSample.java

Execute the java class to get the output.

C:\raji\blog>java AtomicSample

The Final Count is: 640

This is the simple way of using atomic classes in java program. Hope, you understood this. Next part gives the remaining parts of thread synchronization. Keep reading!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Java NIO examples to illustrate channels and buffers.

How to write your first XML program?