Can 2 Threads Access the Same Variable at the Same Time

Java - Thread Synchronization


When nosotros start 2 or more than threads within a program, there may be a state of affairs when multiple threads try to access the same resources and finally they can produce unforeseen issue due to concurrency issues. For example, if multiple threads try to write within a aforementioned file and then they may corrupt the data because ane of the threads can override data or while ane thread is opening the same file at the same time another thread might be endmost the same file.

So there is a need to synchronize the action of multiple threads and make sure that only 1 thread can access the resource at a given point in time. This is implemented using a concept chosen monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

Java programming language provides a very handy style of creating threads and synchronizing their task by using synchronized blocks. You continue shared resources within this cake. Following is the general course of the synchronized statement −

Syntax

synchronized(objectidentifier) {    // Access shared variables and other shared resources }        

Hither, the objectidentifier is a reference to an object whose lock associates with the monitor that the synchronized statement represents. Now we are going to see two examples, where nosotros volition print a counter using 2 different threads. When threads are not synchronized, they impress counter value which is non in sequence, but when we print counter past putting inside synchronized() cake, then it prints counter very much in sequence for both the threads.

Multithreading Example without Synchronization

Here is a simple example which may or may non print counter value in sequence and every time we run it, information technology produces a dissimilar result based on CPU availability to a thread.

Case

class PrintDemo {    public void printCount() {       try {          for(int i = 5; i > 0; i--) {             System.out.println("Counter   ---   "  + i );          }       } grab (Exception e) {          System.out.println("Thread  interrupted.");       }    } }  form ThreadDemo extends Thread {    individual Thread t;    individual String threadName;    PrintDemo  PD;     ThreadDemo( Cord name,  PrintDemo pd) {       threadName = proper noun;       PD = pd;    }        public void run() {       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 grade TestThread {    public static void chief(Cord args[]) {        PrintDemo PD = new PrintDemo();        ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );       ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );        T1.kickoff();       T2.commencement();        // wait for threads to end          try {          T1.bring together();          T2.bring together();       } catch ( Exception e) {          System.out.println("Interrupted");       }    } }        

This produces a different issue every time you run this program −

Output

Starting Thread - one Starting Thread - ii Counter   ---   five Counter   ---   four Counter   ---   3 Counter   ---   5 Counter   ---   2 Counter   ---   ane Counter   ---   4 Thread Thread - one  exiting. Counter   ---   3 Counter   ---   2 Counter   ---   1 Thread Thread - 2  exiting.        

Multithreading Example with Synchronization

Here is the aforementioned case which prints counter value in sequence and every time we run it, information technology produces the same outcome.

Example

class PrintDemo {    public void printCount() {       attempt {          for(int i = 5; i > 0; i--) {             System.out.println("Counter   ---   "  + i );          }       } grab (Exception east) {          System.out.println("Thread  interrupted.");       }    } }  form ThreadDemo extends Thread {    private Thread t;    private Cord threadName;    PrintDemo  PD;     ThreadDemo( String name,  PrintDemo pd) {       threadName = proper name;       PD = pd;    }        public void run() {       synchronized(PD) {          PD.printCount();       }       Arrangement.out.println("Thread " +  threadName + " exiting.");    }     public void start () {       Arrangement.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();       } grab ( Exception due east) {          System.out.println("Interrupted");       }    } }        

This produces the aforementioned result every fourth dimension yous 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   ---   ane Thread Thread - 2  exiting.        

java_multithreading.htm

Useful Video Courses


Java Date and Time Online Training

Video

Java Servlet Online Training

Video

JavaScript Online Training

Video

Java Essential Training

Video

Java Essentials Online Training

Video

cobbthys1968.blogspot.com

Source: https://www.tutorialspoint.com/java/java_thread_synchronization.htm

0 Response to "Can 2 Threads Access the Same Variable at the Same Time"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel