document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package Demo5;
  2.  
  3. /**
  4.  * Title -- Advanced Java_ Multi-threading Part 3 -- The Synchronized Keyword
  5.  * Note:-- Basic Thread synchronization
  6.  * @author Bapa
  7.  * Every object in java has a intransit lock one thread can aquare at a time lock of an object.
  8.  */
  9. public class App {
  10.  
  11.     private int count = 0;
  12.  
  13.     public synchronized void increement() {
  14.         count++;
  15.     }
  16.  
  17.     public static void main(String[] args) {
  18.         App app = new App();
  19.         app.doWork();
  20.     }
  21.  
  22.     public void doWork() {
  23.         Thread t1 = new Thread(new Runnable() {
  24.             public void run() {
  25.                 for (int i = 0; i < 10000; i++) {
  26.                     increement();
  27.                 }
  28.             }
  29.  
  30.         });
  31.  
  32.         Thread t2 = new Thread(new Runnable() {
  33.             public void run() {
  34.                 for (int i = 0; i < 10000; i++) {
  35.                     increement();
  36.                 }
  37.             }
  38.  
  39.         });
  40.  
  41.         t1.start();
  42.         t2.start();
  43.  
  44.         try {
  45.             t1.join();
  46.             t2.join();
  47.         } catch (InterruptedException e) {
  48.             e.printStackTrace();
  49.         }
  50.  
  51.         System.out.println("Count is " + count);
  52.     }
  53.  
  54. }
');