N个线程轮流打印数字问题
2016-03-26 20:43
232 查看
//一个关于线程的经典面试题,要求用三个线程,按顺序打印1,2,3,4,5.... 71,72,73,74, 75. //线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. //接着再由线程1打印16,17,18,19,20....以此类推, 直到线程3打印到75。 public class Printer implements Runnable { int id; static int num = 1; public Printer(int id) { this.id = id; } @Override public void run() { synchronized (Printer.class) { while (num <= 75) { if (num / 5 % 3 == id) { System.out.print("id" + id + ":"); for (int i = 0; i < 5; i++) System.out.print(num++ + ","); System.out.println(); Printer.class.notifyAll(); } else { try { Printer.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { new Thread(new Printer(0)).start(); new Thread(new Printer(1)).start(); new Thread(new Printer(2)).start(); } }
打印结果:
id0:1,2,3,4,5, id1:6,7,8,9,10, id2:11,12,13,14,15, id0:16,17,18,19,20, id1:21,22,23,24,25, id2:26,27,28,29,30, id0:31,32,33,34,35, id1:36,37,38,39,40, id2:41,42,43,44,45, id0:46,47,48,49,50, id1:51,52,53,54,55, id2:56,57,58,59,60, id0:61,62,63,64,65, id1:66,67,68,69,70, id2:71,72,73,74,75,
相关文章推荐
- Linux下安装matlab(2)
- 浅析关联引用
- APP引导页的实现
- POJ 3061 Subsequence(尺取法)
- Python数据库操作(MySQL)
- codevs1536 海战
- linux网络管理命令
- JAVA多线程开发——线程的创建与运行
- 浙江科技学院第十三届程序设计竞赛 1008:A Heavy Rainy Day【贪心】
- leetcode---Majority Element
- Android应用界面开发_学习笔记_第四周
- 对比DataTable和泛型
- 科学论文写作工具TEX/LaTEX/CTEX
- 开源 E-ChartSdk 的使用方法
- 写在开头的话
- 递归方法产生格雷码
- 听VOA还不如学这些
- 淘宝技术这十年概要
- ASP.NET MVC 3 使用 Razor 如何在 Web.config 宣告預設的 Namespaces
- 具有相同元素的排列组合模板