最近偶遇这道题,网上相似的题都是循环次数不一样。然而我百度搜到的论坛或者博客感觉都不太对,运行有穿插。请给出正确结果。
我们假使所有人都引入了业务对象。
并且我有疑问?感觉题目本意不是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(); } } }
https://www.zhihu.com/questio...
知乎上不是有答案了么。synchronized
是多个线程访问同一个方法时的锁,你这是两个线程访问两个方法,所以根本没起作用。
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 = 1; i <= 50; i++) { try { business.sonBusiness(i); } catch (InterruptedException e) { } } } }).start(); for (int i = 1; i <= 50; i++) { business.mainBusiness(i); } } } class Business { private static Object object = new Object(); public void mainBusiness(int i) throws InterruptedException { synchronized (object) { object.notify(); for (int j = 1; j <= 20; j++) { System.out.println("主线程第" + i + "轮,第" + j + "次"); } object.wait(); } } public void sonBusiness(int i) throws InterruptedException { synchronized (object) { object.notify(); for (int j = 1; j <= 30; j++) { System.err.println("子线程第" + i + "轮,第" + j + "次"); } object.wait(); } } } 你用this也没关系,你这就是一个对象锁,所以不会出现多个对象多个锁的问题,你穿插的问题在于你的唤醒和等待写错了,不能又唤醒又等待,这样有什么意义。先唤醒执行代码,执行完再等待。
你的代码看起来没有问题,不过System.out
和err
是两个不同的流,可能是这两个流输出的时候有的问题吧。个人认为程序是按照你的想法跑了,可是输出却没有正确的输出吧。