Java Concurrency Synchronization
w3hello.com logo
Java Basics
Java Introduction
Java Installation
Java Operators
Java Variable Types
Java Loops
Java For Loop
Java While Loop
Java do while loop
Java Continue
Java JButton
Java JTextArea
Java Logical Operators
switch statement in java
Java JPasswordField
Java Year
Java Constructor
Java Basic Syntax
Java JComboBox
Java JToolBar
Java if Statements
Java JMenuBar, JMenu and JMenuItem
Java JDialog
Java JToggleButton
Java JFrame
Java Zip Exceptions
Java DIP - Enhancing Image Brightness
Java JFileChooser
Java Concurrency ExecutorService Interface
Java throw exception
LinkedHashMap in Java
Java Digital Watch
Java instanceof
Java AWT Button
Java For Complete Beginners - loops and arrays
Array vs ArrayList in Java
java.util.Calendar
Java JColorChooser
Java URL Processing
Guide to Java Exception Hierarchy
Java Concurrency ConcurrentMap Interface
Synchronization in Java
Java Internationalization
Java Fetch Image from Oracle Database
Unicode System in Java
Java ActionListener
java.lang.reflect - Interfaces
Java Thread Pool | Thread Pooling in Java
Java Graphics in Applet
Java Convert int to long
Java JSpinner
Java Primitive data type
Java Numeric Literals with Underscore
Inter-thread communication in Java
The Tetris game in Java Swing
Java Applet Basics
Java Convert Binary to Decimal
Static keyword in Java
Java Convert Hex to Decimal
Java JRadioButton
Java XML Overview
Java Concurrency Quick Guide
Java Month enum
Types of Exceptions
Reentrant Monitor in Java
Java Loop Control
Java Access Modifiers
WebSocket in Jetty
Transaction Management in Java JDBC
Java SimpleDateFormat
Java 7 JDBC Improvement
Java FlowLayout
Java AWT Scrollbar
Java Decision Making
Java Database Connectivity with Oracle
Java ZoneId
Java else-if Statements
Java DIP - Laplacian Operator
Top Java Books
Java Date Time - Custom Date Format Patterns
Java static and this Keyword
Java JList
Java Concurrency Lock Interface
Java LocalDate
Creating a thread in Java
Jetty's HTTPClient
Java Package
Displaying image in Applet
Java Overriding
Java AWT Choice
Java SAX Parser Overview
Java Save File in Oracle Database
Java Modifier
Java JDesktopPane
Java Inheritance & Polymorphism
Discuss Java Concurrency
this keyword in java
Java KeyListener
Java Online Training
Java iText
History of Java
Java Basics
Previous : Java XPath Parser Overview Next : Java Naming Conventions

Java Concurrency Synchronization


Multithreading Example with Synchronization

Here is the same example which prints counter value in sequence and every time we run it, it produces the same result.

Example

Live Demo
class PrintDemo {
   
   public void printCount() {
      
      try {
         
         for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
         }
      } catch (Exception e) {
         System.out.println("Thread  interrupted.");
      }
   }
}

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   PrintDemo  PD;

   ThreadDemo(String name,  PrintDemo pd) {
      threadName = name;
      PD = pd;
   }
   
   public void run() {
      
      synchronized(PD) {
         PD.printCount();
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }

   public void start () {
      System.out.println("Starting " +  threadName );
      
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      PrintDemo PD = new PrintDemo();

      ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
      ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);

      T1.start();
      T2.start();

      // wait for threads to end
      try {
         T1.join();
         T2.join();
      } catch (Exception e) {
         System.out.println("Interrupted");
      }
   }
}

This produces the same result every time you run this program −

Output

Starting Thread - 1
Starting Thread - 2
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 1  exiting.
Counter   ---   5
Counter   ---   4
Counter   ---   3
Counter   ---   2
Counter   ---   1
Thread Thread - 2  exiting.
Previous : Java XPath Parser Overview Next : Java Naming Conventions
© Copyright 2018 W3Hello Publishing Limited. All rights reserved.
Contact us | Sitemap