4.传统线程同步通信技术
2015-07-10 11:08
197 查看
/** * 传统线程同步通信技术 * * ******************************************* * 经验: * 要用到共同数据(包括共同锁)或共同算法的若干个方法应该 * 归在用一个类身上,这种设计正好体现了高内聚和程序的健壮性。 * * ******************************************* * * @author LiTaiQing */ public class TraditionalThreadCommunication { /************************************************** * 调试小技巧 * 如果由于Console的输出太多而造成面板显示的数据不完整 * 可设置运行前参数设置 * 右键->Run As->Run Configuractions->Common->File * 选择保存的路径即可 * ************************************************** */ /** * 面试题 * ·子线程循环10次,接着主线程循环100,接着又回到子线程循环10次, * ·接着再回到主线程又循环100,如此循环50次,请写出程序 */ public static void main(String[] args){ final Business business = new Business(); new Thread(new Runnable(){ @Override public void run() { for(int i = 1; i <= 50; i++){ business.sub(i); } } }).start(); for(int i = 1; i <= 50; i++){ business.main(i); } } } class Business{ private boolean bShouldSub = true; public synchronized void sub(int i){ /** * 此处将if改为while,增强代码健壮性。 * 防止伪唤醒! */ while(!bShouldSub){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int j = 1; j <= 10; j++){ System.out.println("sub thread sequece of " + j + ",loop of " +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("main thread sequece of " + j + ",loop of " +i); } bShouldSub = true; this.notify(); } }
相关文章推荐
- MYSQL查询重复记录的方法
- activemq 实战三 了解连接器的URI-Understanding connector URIs
- ACM-简单的主题Ignatius and the Princess II——hdu1027
- 你知道什么是Grunt么?
- 长短信发送Emoji 图标被截断的问题分析
- Linux 下 Address already in use 错误的解决
- 等保制度与ISO27001的区别与联系
- 在Java程序中使用数据库的新方法
- JQuery之回到顶部的特效
- java web 监听器listener详解
- 图片的操作
- 3.传统线程互斥技术
- 实例分析用指针访问二维数组的几种方法
- 我的上半年“手相”-----“奔跑中的2015”
- android禁止界面横屏
- Guava 15新特性介绍
- 2.传统定时器技术回顾 - Timer类 TimerTask
- mongodb的基本操作
- 关于<img>标签无法显示名字中带有中文的图片的问题
- GRE写作必备句型