What will be the output of the following code?

import java.util.*;
import java.util.concurrent.*;

class ExampleThread extends Thread {
    private static CountDownLatch latch = new CountDownLatch(1);
    private static Semaphore semaphore = new Semaphore(1, true);

    private int type;
    private String[] letters = { "A", "B", "C", "D", "E" };

    ExampleThread(int type) {
        super();
        this.type = type;
    }

    public void run() {
        try {
            if (type == 0) {
                semaphore.acquire();
                latch.countDown();
            } else {
                latch.await();
                semaphore.acquire();
            }

            for (int i = 0; i < 5; i++) {
                if (type == 0) {
                    System.out.print(i);
                } else {
                    System.out.print(letters[i]);
                }
                Thread.sleep(100);
            }
        } catch (Exception ex) {
            System.out.println("Exception 2");
        }
        semaphore.release();
    }


    public static void main(String[] args) {
        new ExampleThread(1).start();
        new ExampleThread(0).start();
    }
}
Explanation
The code flow is as follows:
The main method creates 2 threads, setting their type (via the ExampleThread constructor) to 0 and 1.
When the thread starts it checks for its type, if it's 0 - it tells the CountDownLatch object to decrement it's count field and acquires the semaphore. After the run() method execution is finished, the semaphore is released.
If the thread type is 1 - it checks the latch object's count field. If it equals to 0 - the thread execution continues, otherwise - it waits for it to become 0. Obviously, in order to acquire the semaphore, it should first be released by the 0 type thread.
Consequently, starting the code would have the 0 type thread print the numbers from 0 to 4, and the 1 type thread wait for it to finish. After the 0 type thread has released both the latch and the semaphore, the 1 type resumes and prints the letters array contents.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты