Advertisement
xeritt

Test join method

Nov 12th, 2017
255
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Sync implements Runnable{
  2.   private Thread monitor;
  3.   public  Sync setMonitor(Thread mon){
  4.       monitor = mon;
  5.       return this;
  6.   }
  7.    
  8.   public void run() {    
  9.     try {
  10.         System.out.println(Thread.currentThread().getName() + ": start");
  11.         if (monitor == null)
  12.             Thread.sleep(1000);
  13.         else   
  14.             monitor.join(); //ожидание выполнения потока monitor
  15.         System.out.println(Thread.currentThread().getName() + ": end");
  16.     } catch (InterruptedException e) {
  17.         e.printStackTrace();
  18.     }
  19.   }
  20. }
  21.  
  22. public class TestJoinMethod{
  23.   public static void main(String[] args) throws Exception{
  24.     Thread ta = new Thread(new Sync(), "threadA");
  25.     Thread tb = new Thread(new Sync().setMonitor(ta), "threadB");
  26.     ta.start();
  27.     tb.start();
  28.     try {
  29.         tb.join(); //ожидание выполнения потока tb
  30.     } catch (InterruptedException e) {
  31.         e.printStackTrace();
  32.     }
  33.     System.out.println(Thread.currentThread().getName() + ": end");
  34.  }
  35. }
Advertisement
RAW Paste Data Copied
Advertisement