Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.CountDownLatch;
- public class App {
- static class ShouldRunFirst extends Thread {
- private final CountDownLatch latch;
- ShouldRunFirst(CountDownLatch latch) {
- this.latch = latch;
- }
- @Override
- public void run() {
- System.out.println("first thread started doing its work ....");
- // your logic goes here
- System.out.println("first thread done");
- latch.countDown();
- }
- }
- static class ShouldRunSecond extends Thread {
- @Override
- public void run() {
- System.out.println("second thread started doing its work ....");
- // your logic goes here
- System.out.println("second thread done");
- }
- }
- public static void main(String[] args) {
- try {
- // start first job
- var firstThreadCompletion = new CountDownLatch(1);
- var t1 = new ShouldRunFirst(firstThreadCompletion);
- t1.start();
- // wait until first job is done, after that start the second one
- firstThreadCompletion.await();
- var t2 = new ShouldRunSecond();
- t2.start();
- // wait until both jobs are finished
- t1.join();
- t2.join();
- System.out.println("main thread finished");
- } catch (InterruptedException e) {
- System.err.println("oops, something interrupted main thread");
- throw new RuntimeException(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement