#201 Printing print from Multiple Threads

Companies:
Sberbank
Themes:
JavaConcurrencyCode Review

How many times will the word print be printed?

class AtomicPrinter implements Runnable {
    private final AtomicBoolean printMe = new AtomicBoolean(true);

    @Override
    public void run() {
        if (printMe.get()) {
            System.out.println("print");
            printMe.set(false);
        }
    }
}

public class AtomicPrinterTest {
    public static void main(String[] args) {
        var printer = new AtomicPrinter();
        var printers = new ArrayList<Thread>();

        for (int i = 0; i < 100; i++) {
            printers.add(new Thread(printer));
        }

        // How many times will the word print be printed?
        for (int i = 0; i < 100; i++) {
            printers.get(i).start();
        }
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in