Advertisement
xeritt

Test synchronized method

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