#201 Printing print from Multiple Threads
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor