Search This Blog

Tuesday 19 August 2014

Restrict access to Shared Data - Thread Synchronization - JAVA

How to Restrict access to shared data one thread at a time in Java - Thread Synchronization

When a data is being shared among different threads, we need to restrict the access of one thread at a time to avoid race conditions.


This program shows how to Restrict access to a shared data among different threads in Java by using thread synchronization..

ThreadCreationJava.java

public class Main {
 public static void main(String args[]){
  TargetClass target = new TargetClass();
  MyThread t1 = new MyThread(1,target); //thread id , shared object
  MyThread t2 = new MyThread(2, target);
  MyThread t3 = new MyThread(3, target);
  
  t1.start();
  t2.start();
  t3.start();
 }
}

MyThread.java

public class MyThread extends Thread {
 private int threadId;
 private TargetClass target;
 
 public MyThread(int i, TargetClass target2) {
  threadId = i; target = target2;
 }

 @Override
 public void run() {
  
  synchronized (target) { // we place shared data here. Now only one thread can access shared data at a time.
   
   try {
    sleep(2000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   target.call(threadId);
  }
  
 }
}

TargetClass.java

public class TargetClass {
 
 public void call(int threadId){
  System.out.println("Function called from thread " + threadId);
 }
 
}

No comments:

Post a Comment