# Threads Synchronization in Java (with example)

In 
Published 2022-12-03

This tutorial will explain to you how to synchronize threads in Java and will present you an example.

Multithreading refers to two or more tasks executing concurrently within a single process. A thread is an independent path of execution within a process. Many threads can run concurrently within a process. There can be multiple processes inside the OS.

NOTES:

  • Threads share the same address space and therefore can share both data and code
  • Cost of communication between the threads is low.
  • Threads allow different tasks to be performed concurrently

There are two ways to create thread in java:

  1. by extending the Thread class (java.lang.Thread)
  2. by implementing the Runnable interface (java.lang.Runnable)

Here is an example of using Threads synchronization in Java using the "extends Thread" method (the "implements Runnable" method is similar):

package threads.java.example;
 
class PrintValues {
 
    // This synchronized method "lock" the "PrintValues" objects
    // Remark that this is a static class/ method
    static synchronized void printValues(String threadName){
         
        for (int i = 1; i < 12; i++) {
             System.out.println("printValues   --->   "  + i + " >>> FROM : "+threadName);
        }
   }
}
package threads.java.example;
 
public class ThreadClass extends Thread {
       private Thread thread;
       private String threadName;
        
       ThreadClass( String name) {
          threadName = name;
          System.out.println("Creating " +  threadName );
       }
        
       public void run() {
          PrintValues printValues = new PrintValues();
          System.out.println(threadName + " is running ...");
         
          printValues.printValues(threadName);
           
          System.out.println( threadName + " has been finished.");
       }
        
       public void start () {
          System.out.println("Start " +  threadName );
          if (thread == null) {
              thread = new Thread (this, threadName);
              thread.start ();
          }
       }
    }
package threads.java.example;
 
public class ThreadsInJavaExample {
 
       public static void main(String args[]) {
          ThreadClass T1 = new ThreadClass("Thread A");
          T1.start();
 
          ThreadClass T2 = new ThreadClass("Thread B");
          T2.start();
       }   
    }

And here is the result of the execution: