Saturday, September 6, 2014

3. Synchronized Keyword

Java Multithreading: Synchronized
This is the third part of our advanced Java multi-threading tutorial. In this tutorial we look at using the synchronized keyword to coordinate actions between threads and prevent them screwing up each other’s work.

Code For This Tutorial
public class App {
    private int count = 0;
    
    public synchronized void increment() {
        count++;
    }

      public static void main  (String[] args){
            App app = new App();
            app.doWork();
      }
     
      public void doWork(){
            Thread t1= new Thread (new Runnable(){
                  public void run(){
                        for(int i=0; i<10000; i++) {
                              increment();
                              //count++;
                        }
                  }
            });

            Thread t2= new Thread (new Runnable(){
                  public void run(){
                        for(int i=0; i<10000; i++) {
                              increment();
                              //count++;
                        }
                  }
            });        
           
            t1.start();
            t2.start();
           
           
            try {
                  t1.join();
                  t2.join();
            } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }

           
            System.out.println("Count is : " + count);
      }

}

No comments:

Post a Comment