Chinaunix首页 | 论坛 | 博客
  • 博客访问: 15744
  • 博文数量: 3
  • 博客积分: 126
  • 博客等级: 民兵
  • 技术积分: 25
  • 用 户 组: 普通用户
  • 注册时间: 2011-07-19 13:53
文章分类
文章存档

2011年(3)

最近访客

分类:

2011-12-01 22:06:47

原文地址:java多线程 面试题目 作者:xueliangfei

采用Java 多线程技术,设计实现一个符合生产者和消费者问题的程序。对一个对象(枪膛)进行操作,其最大容量是12颗子弹。生产者线程是一个压入线程,它不断向枪膛中压入子弹;消费者线程是一个射出线程,它不断从枪膛中射出子弹。
  1. public class ThreadCaseDemo01
  2. {
  3. /**
  4. *
  5. *
  6. * 采用Java
  7. * 多线程技术,设计实现一个符合生产者和消费者问题的程序。对一个对象(枪膛)进行操作,其最大容量是12颗子弹。
  8. * 生产者线程是一个压入线程
  9. * 它不断向枪膛中压入子弹;消费者线程是一个射出线程,它不断从枪膛中射出子弹。
  10. */
  11. public static void main(String[] args)
  12. {
  13. Gun i = new Gun();
  14. Producter pro = new Producter(i);
  15. Consumer con = new Consumer(i);
  16. new Thread(pro).start();
  17. new Thread(con).start();
  18. }

  19. }
  20. //////////////////////////////////////////////
  21. public class Gun
  22. {
  23. private String name;
  24. private String content;
  25. private boolean flag = false;

  26. public synchronized void set(String name, String content)
  27. {
  28. if (flag)
  29. {
  30. try
  31. {
  32. super.wait();
  33. } catch (InterruptedException e)
  34. {
  35. e.printStackTrace();
  36. }
  37. }
  38. this.setName(name);
  39. this.setContent(content);
  40. flag = true;//保证生产者进入等待状态
  41. super.notify();

  42. }

  43. public synchronized void get()
  44. {
  45. if (!flag)
  46. {
  47. try
  48. {
  49. super.wait();
  50. } catch (InterruptedException e)
  51. {
  52. e.printStackTrace();
  53. }
  54. }
  55. System.out.println(this.getName() + "-->" + this.getContent());
  56. flag = false;//保证消费者进入等待状态
  57. super.notify();
  58. }

  59. public String getName()
  60. {
  61. return name;
  62. }

  63. public void setName(String name)
  64. {
  65. this.name = name;
  66. }

  67. public String getContent()
  68. {
  69. return content;
  70. }

  71. public void setContent(String content)
  72. {
  73. this.content = content;
  74. }

  75. }
  76. //////////////////////////////////////
  77. public class Consumer implements Runnable
  78. {
  79. private Gun gun=null;
  80. public Consumer (Gun gun)
  81. {
  82. this.gun=gun;
  83. }
  84. public void run()
  85. {
  86. for(int i=0;i<12;i++)
  87. {
  88. this.gun.get();
  89. }

  90. }
  91. }
  92. ///////////////////////////////////////
  93. public class Producter implements Runnable
  94. {
  95. private Gun gun=null;
  96. public Producter(Gun gun)
  97. {
  98. this.gun=gun;
  99. }

  100. public void run()
  101. {
  102. boolean flag=false;
  103. for(int i=0;i<12;i++)
  104. {

  105. if(flag)
  106. {

  107. this.gun.set("楼主", "给枪上了一发子弹");
  108. flag=false;

  109. }
  110. else
  111. {
  112. this.gun.set("我","给了楼主一枪");
  113. flag=true;
  114. }

  115. }
  116. }
  117. }
阅读(2358) | 评论(0) | 转发(0) |
0

上一篇:vmvare使用中常用

下一篇:没有了

给主人留下些什么吧!~~