Java - the synchronized keyword

  1. /** 
  2.  * Java - the synchronized keyword 
  3.  * Sometimes, you only want to prevent multiple thread access to part of the code inside a method instead of the entire method. 
  4.  * The section of code you want to isolate this way is called 'critical section' and is created using the synchronized keyword. 
  5.  */ 
  6. class ClassA  
  7.     private static int id = 0
  8.      
  9.     public void getId(String threadName) 
  10.     { 
  11.         /** 
  12.          * Here, synchronized is used to specify the object whose lock is being used to synchronize the enclosed code. 
  13.          * This is also called a synchronized block; before it can be entered, the lock must be acquired a lock on a object. 
  14.          * If some other task already has his lock, then the critical section cannot be entered until the lock is released. 
  15.          */ 
  16.         synchronized (this/* an object here */
  17.         { 
  18.             id++; 
  19.             try  
  20.             { 
  21.                 Thread.sleep(1); 
  22.             } catch (InterruptedException e)  
  23.             { 
  24.                 e.printStackTrace(); 
  25.             } 
  26.             System.out.println("thread name: " + threadName + "\n" + "id: " + id); 
  27.         } 
  28.     } 
  29.  
  30. public class Main implements Runnable 
  31.     public static void main(String[] args)  
  32.     { 
  33.         Main m1 = new Main(); 
  34.         Main m2 = new Main(); 
  35.          
  36.         Thread t1 = new Thread(m1); 
  37.         Thread t2 = new Thread(m2); 
  38.          
  39.         t1.start(); 
  40.         t2.start(); 
  41.     } 
  42.  
  43.     @Override 
  44.     public void run()  
  45.     { 
  46.         try  
  47.         { 
  48.             new ClassA().getId(Thread.currentThread().getName()); 
  49.         }  
  50.         catch (Exception e)  
  51.         { 
  52.             e.printStackTrace(); 
  53.         } 
  54.     } 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章