线程间通信
来源:互联网 发布:关于孙悟空的网络歌曲 编辑:程序博客网 时间: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
- 线程同步--线程间通信
- 线程同步--线程间通信
- JAVASE线程---线程间通信
- JAVA线程-线程间通信
- 线程3:线程间通信
- 线程与线程间通信
- 线程间通信
- c#线程间通信
- VC 线程间通信
- 线程间通信 ManualResetEvent
- java 线程间通信
- android线程间通信
- VC 线程间通信
- 线程间通信方式
- QT---线程间通信
- Android线程间通信
- 线程间的通信
- linux线程间通信
- 初识elixir
- Android 自定义ViewGroup中onDraw方法不执行的解决方法
- 组态王和stm32之间通信笔录
- java之NIO select基本设计思路梳理
- [leetcode]341. Flatten Nested List Iterator
- 线程间通信
- Android常见问题汇总
- mysql之联表查询回顾
- Lucene基础
- 荷马史诗(NOI2015)提高组
- android代码获取layout和设置margin
- 安卓异步消息处理机制源码流程
- lcd常用接口
- 电商平台运营8步总结