package com.x.test; /** * @author lelonta * @version 1.0 */ public class ThreadCommunicate { //子线程循环10次 主线程循环100次 然后如此反复50次 public static void main(String[] args) { new ThreadCommunicate().init(); } public void init() { final business bun = new business(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 50; i++) { bun.sub(i); } } }) { }.start(); new Thread(new Runnable() { @Override public void run() { for (int i = 1; i <= 50; i++) { bun.main(i); } } }) { }.start(); //本身main方法就是一个线程 // for (int i = 1; i <= 50; i++) { // // bun.main(i); // // } } //内部类 class business { //标识符 private boolean bShouldSub = true; public synchronized void sub(int i) { while (!bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("子线程"+j+",循环次数"+i); } bShouldSub = false; this.notify(); } public synchronized void main(int i) { while (bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 100; j++) { System.out.println("主线程"+j+",循环次数"+i); } bShouldSub = true; this.notify(); } } }
子线程循环10次 主线程循环100次 然后如此反复50次
最新推荐文章于 2020-12-03 10:26:28 发布