线程间通信

来源:互联网 发布:关于孙悟空的网络歌曲 编辑:程序博客网 时间:2024/06/06 16:58
同学出去面试,遇到的一道面试题:先让子线程执行10次,再让主线程执行100次,之后子线程执行10次,主线程再执行100次,如此循环50次。
代码如下:
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();}}
把主线程和子线程写在一个类中,体现了程序的高内聚。
0 0