package com.thread;public class ThreadCommunication2 { public static void main(String[] args) { final Bussiness b = new Bussiness(); //子线程 new Thread(new Runnable() { public void run() { for (int i = 1; i <= 50; i++) { b.sub(i); } } }).start(); //主线程 for (int i = 1; i <= 50; i++) { b.main(i); } }}class Bussiness { PRivate boolean flag = true; public synchronized void sub(int i) { //如果不是自己 ,就等待 if (!flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("子线程循环" + j + "次,总循环" + i + "次"); } flag = false; this.notify(); } public synchronized void main(int i) { if (flag) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 100; j++) { System.out.println("主线程循环" + j + "次,总循环" + i + "次"); } flag = true; this.notify(); }}把主线程和子线程写在一个类中,体现了程序的高内聚。
新闻热点
疑难解答