Answer the question
In order to leave comments, you need to log in
How to make the threads work strictly alternately?
Hello. I have 2 classes, one only prints 'A', the other prints 'B'. I need to make them work alternately, i.e. output to the console: ABABAB ... So that there are no consecutive letters of the same letter. What am I doing wrong?
public class LetterA extends Thread {
private final static Object lock = new Object();
public LetterA() {
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
synchronized (lock) {
if (i / 2 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else System.out.print("A ");
lock.notifyAll();
}
}
}
}
private static void printLetters() {
LetterA letterA = new LetterA();
LetterB letterB = new LetterB();
letterA.start();
letterB.start();
Answer the question
In order to leave comments, you need to log in
An uncomfortable question - why then do parallelism at all, if the code must be executed synchronously?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question