同步两个线程打印到stderr

时间:2023-01-21 21:01:54

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

我的理解是使用java synchronize和notify()以及wait()方法同步两个线程的工作方式如下:

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 .

然而,我看到的输出(见下文)告诉我,同步不符合我的预期。我认为主线程和新线程可以“逐个”运行,在大多数情况下它们可以运行。但我得到以下输出。我不知道如何解释,请帮我一把。

同步两个线程打印到stderr

1 个解决方案

#1


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.

我想这是因为你同时将它们打印到System.out和System.errat。在IDE中,它们可能是相同的控制台,但不能很好地同步。

#1


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.

我想这是因为你同时将它们打印到System.out和System.errat。在IDE中,它们可能是相同的控制台,但不能很好地同步。