Java classic question: sub-thread runs the main thread 30 times and the main thread 40 times, so it loops 50 times?

  java, question

Recently, I came across this problem. Similar problems on the Internet all have different cycles. However, the forums or blogs I found on Baidu are not quite right, and the operation is interspersed. Please give the correct results.
Let’s assume that everyone has introduced business partners.

And I have questions? I don’t think the topic was meant to be new Thread () in front.
Some people on the Internet use flag bits to prevent false awakening, and locks are placed on the method. Does it make sense?

public class Test {
 
 public static void main(String[] args) throws InterruptedException {
 final Business business = new Business();
 //child thread
 new Thread(new Runnable() {
 @Override
 public void run() {
 for (int i = 0;   i < 50;  I plus)
 try {
 business.sonBusiness(i);
 } catch (InterruptedException e) {
 bracket
 bracket
 bracket
 }).start();
 for (int i = 0;   i < 50;  I plus)
 business.mainBusiness(i);
 bracket
 
 bracket
 
 bracket
 
 class Business {
 public void mainBusiness(int i) throws InterruptedException {
 synchronized (this) {
 for (int j = 1;   j <= 20;  J plus)
 System.out.println ("main thread" plus i plus "round and" plus j plus "round");
 bracket
 this.notify();
 this.wait();
 bracket
 
 bracket
 
 public void sonBusiness(int i) throws InterruptedException {
 synchronized (this) {
 for (int j = 1;   j <= 30;  J plus)
 System.err.println ("sub-thread's" plus i plus "round and" plus j plus "round");
 bracket
 this.notify();
 this.wait();
 bracket
 bracket
 bracket

https://www.zhihu.com/questio …

Your code looks fine, butSystem.outAndErrIt is two different streams, which may be some problems when the two streams are output. Personally, I think the program ran according to your idea, but the output was not correct.