Advertisement
dburyak

Untitled

May 8th, 2021
894
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.56 KB | None | 0 0
  1. import java.util.concurrent.CountDownLatch;
  2.  
  3. public class App {
  4.  
  5.     static class ShouldRunFirst extends Thread {
  6.         private final CountDownLatch latch;
  7.  
  8.         ShouldRunFirst(CountDownLatch latch) {
  9.             this.latch = latch;
  10.         }
  11.  
  12.         @Override
  13.         public void run() {
  14.             System.out.println("first thread started doing its work ....");
  15.             // your logic goes here
  16.             System.out.println("first thread done");
  17.             latch.countDown();
  18.         }
  19.     }
  20.  
  21.     static class ShouldRunSecond extends Thread {
  22.  
  23.         @Override
  24.         public void run() {
  25.             System.out.println("second thread started doing its work ....");
  26.             // your logic goes here
  27.             System.out.println("second thread done");
  28.         }
  29.     }
  30.  
  31.     public static void main(String[] args) {
  32.         try {
  33.             // start first job
  34.             var firstThreadCompletion = new CountDownLatch(1);
  35.             var t1 = new ShouldRunFirst(firstThreadCompletion);
  36.             t1.start();
  37.  
  38.             // wait until first job is done, after that start the second one
  39.             firstThreadCompletion.await();
  40.             var t2 = new ShouldRunSecond();
  41.             t2.start();
  42.  
  43.             // wait until both jobs are finished
  44.             t1.join();
  45.             t2.join();
  46.             System.out.println("main thread finished");
  47.         } catch (InterruptedException e) {
  48.             System.err.println("oops, something interrupted main thread");
  49.             throw new RuntimeException(e);
  50.         }
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement