/** * 子线程循环5次,接着主线程循环10次,接着又回到子线程循环5次, * 接着再回到主线程又循环10次,如此循环8次。 */ public class UserThread { private static class Business { // 标识子线程调用方法是否被调用 private boolean subIsCallFlag = true; public synchronized void subExecute(int i) { while (!subIsCallFlag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 5; j++) { System.out.println("子线程循环 " + (j + 1) + "次"); } subIsCallFlag = false; this.notify(); } public synchronized void mainExecute(int i) { while (subIsCallFlag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 0; j < 10; j++) { System.out.println("主线程执行 " + (j + 1) + "次"); } System.out.println("====================================" + (i + 1) + "轮"); subIsCallFlag = true; this.notify(); } } public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { @Override public void run() { for(int i = 0; i < 8; i++) { business.subExecute(i); } } }).start(); for(int i = 0; i < 8; i++) { business.mainExecute(i); } } }
笔试题:子线程循环5次,接着主线程循环10次,接着又回到子线程循环5次,接着再回到主线程又循环10次,如此循环8次。
最新推荐文章于 2022-12-24 20:49:50 发布