Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2173683
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: Java

2011-05-13 12:15:05

  1. public class ProducerConsumer {
  2. public static void main(String[] args) {
  3. SyncStack ss = new SyncStack();
  4. Producer p = new Producer(ss);
  5. Consumer c = new Consumer(ss);
  6. new Thread(p).start();
  7. new Thread(p).start();
  8. new Thread(p).start();
  9. new Thread(c).start();
  10. }
  11. }
  12. class WoTou {
  13. int id;
  14. WoTou(int id) {
  15. this.id = id;
  16. }
  17. public String toString() {
  18. return "WoTou : " + id;
  19. }
  20. }
  21. class SyncStack {
  22. int index = 0;
  23. WoTou[] arrWT = new WoTou[6];
  24. public synchronized void push(WoTou wt) {
  25. while (index == arrWT.length) {
  26. try {
  27. this.wait();
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. this.notifyAll();
  33. arrWT[index] = wt;
  34. index++;
  35. }
  36. public synchronized WoTou pop() {
  37. while (index == 0) {
  38. try {
  39. this.wait();
  40. } catch (InterruptedException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. this.notifyAll();
  45. index--;
  46. return arrWT[index];
  47. }
  48. }
  49. class Producer implements Runnable {
  50. SyncStack ss = null;
  51. Producer(SyncStack ss) {
  52. this.ss = ss;
  53. }
  54. public void run() {
  55. for (int i = 0; i < 20; i++) {
  56. WoTou wt = new WoTou(i);
  57. ss.push(wt);
  58. System.out.println("生产了:" + wt);
  59. try {
  60. Thread.sleep((int) (Math.random() * 200));
  61. } catch (InterruptedException e) {
  62. e.printStackTrace();
  63. }
  64. }
  65. }
  66. }
  67. class Consumer implements Runnable {
  68. SyncStack ss = null;
  69. Consumer(SyncStack ss) {
  70. this.ss = ss;
  71. }
  72. public void run() {
  73. for (int i = 0; i < 20; i++) {
  74. WoTou wt = ss.pop();
  75. System.out.println("消费了: " + wt);
  76. try {
  77. Thread.sleep((int) (Math.random() * 1000));
  78. } catch (InterruptedException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. }
  83. }

 threadDemo.zip   

转自:http://hi.baidu.com/greatwqs/blog/item/744fa65936dec1d49c820480.html

阅读(1620) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~