K
K
Koshkasobaka2020-12-02 14:36:58
Java
Koshkasobaka, 2020-12-02 14:36:58

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();
            }
        }
}
    }


in main:
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

1 answer(s)
J
JaktensTid, 2020-12-02
@JaktensTid

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 question

Ask a Question

731 491 924 answers to any question