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 .