Advertisement
xeritt

Test synchronized block

Nov 10th, 2017
236
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Data{ public String name;}
  2. class Sync implements Runnable{
  3.   private Data data;
  4.   Sync(Data dt){data = dt;}
  5.   public void run() {    
  6.         synchronized(data){
  7.             data.name = Thread.currentThread().getName();
  8.             print("before: " + data.name);
  9.             try {
  10.                 Thread.sleep(1000);
  11.             } catch (InterruptedException x) {
  12.             }
  13.             print("after: " + data.name);
  14.         }
  15.   }
  16.  
  17.   public static void print(String msg) {
  18.     System.out.println(Thread.currentThread().getName() + ": " + msg);
  19.   }
  20. }
  21.  
  22. public class TestSynchronized{
  23.   public static void main(String[] args) throws Exception{
  24.     Data id = new Data();
  25.     Sync runA = new Sync(id);
  26.     Sync runB = new Sync(id);
  27.     Thread ta = new Thread(runA, "threadA");
  28.     Thread tb = new Thread(runB, "threadB");
  29.     ta.start();
  30.     tb.start();
  31.  }
  32. }
Advertisement
RAW Paste Data Copied
Advertisement