-1

There is an array with strings "A", "B" and "A, B" (there are many repeated). I need to make 2 threads A and B, each of which will independently output its strings in the correct order (as in the original array, general in any). Did I get it right, the best way to implement this is with wait() and notify()? As long as the lines correspond to the thread, output them, and after that put wait(), at that point the second thread starts outputting its lines before the same wait(). But I don't understand where to call notify.

upd: example: for String[] arr = {"A", "A", "A, B", "B", "A", "B"} I want output like

A         A
A         A
A         B
B         A
B         B
A         A
B   or    B

All "A" should be printed by Thread A, all "B" should be printed by Thread B. If the value in the array is common ("A, B"), then the order of printing is not important, but the letters must be after all the previous and before the next elements.

ewl1
  • 17
  • 3
  • I suggest you add an example of what you except that will happen for different inputs and what you tried to do as your question isn't clear – Moshe9362 May 24 '22 at 20:02
  • @Moshe9362 ok, I've added an example – ewl1 May 24 '22 at 21:06
  • The best way to do this is with a single thread. If the other thread must wait while each thread is active, using two threads only adds complexity with no benefit. – erickson May 25 '22 at 16:01
  • I understand this, but I need to use 2 threads – ewl1 May 25 '22 at 21:03

1 Answers1

0

As far as I understood your question you have an array, for example, new String[]{"A","A","B","A","B"} and you want that thread a reads all "A"'s until a "B" is the next string. You already mentioned the two keywords wait() and notify(), these are methods implemented by the object class, so every object has both the wait() and notify() method wait() - let the current thread wait until a notify() notify() - awakens a thread waiting for a notify() called on the specific object Everytime one of your threads calls wait(), you first have to notify the other thread, to prevent a deadlock (both threads waiting) At the end it will work like this:

  • thread a - started
  • thread b - started
  • thread b - wait()
  • thread a - read "A"
  • thread a - read "A"
  • thread a - notify()
  • thread a - wait()
  • thread b - read "B"
  • thread b - notify()
  • thread b - wait()
  • thread a - read "A"
  • thread a - notify()
  • thread a - wait()
  • thread b - read "B"

Note that this order could vary a bit, cause you don't know when exactly threads gets CPU time

Sebastian
  • 153
  • 1
  • 10