最近偶遇這道題,網上相似的題都是循環次數不一樣。然而我百度搜到的論壇或者博客感覺都不太對,運行有穿插。請給出正確結果。
我們假使所有人都引入了業務對象。
并且我有疑問?感覺題目本意不是new Thread()放在前面。
網上有人做法是用標志位防止虛假喚醒,還有鎖放在方法上的。是否有道理?
public class Test {
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();
}
}
}