-1

It is my understanding that synchronization of two threads using java synchronize and notify() and wait() methods works like this:

public class Tester {
    public static void main(String[] args) throws InterruptedException {
        final Business business = new Business();
        // 子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    try {
                        business.sonBusiness(i);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }).start();
        for (int i = 0; i < 50; i++) {
            business.mainBusiness(i);
        }
    }
}
class Business {
    public void mainBusiness(int i) throws InterruptedException {
        synchronized (this) {
            for (int j = 1; j <= 20; j++) {
                System.out.println("主线程第" + i + "轮,第" + j + "次");
            }
            this.notify();
            this.wait();
        }
    }
    public void sonBusiness(int i) throws InterruptedException {
        synchronized (this) {
            for (int j = 1; j <= 30; j++) {
                System.err.println("子线程第" + i + "轮,第" + j + "次");
            }
            this.notify();
            this.wait();
        }
    }
}

However the output that I see (see below) tells me that the synchronization is not workign as I expect. I think the main thread and the new thread may run "one by one" and in most cases they do. But I get the following output. I don't know how to explain it , please give me a hand .

enter image description here

Matthias
  • 3,228
  • 2
  • 23
  • 40
passion
  • 1,154
  • 6
  • 15

1 Answers1

3

I guess it's because you are printing them to System.out and System.errat the same time. In IDE they may be the same console, but not synchronized very well.

grape_mao
  • 1,103
  • 1
  • 7
  • 15