A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© EDDY_Liang 中级黑马   /  2014-9-28 12:38  /  928 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 EDDY_Liang 于 2014-9-28 14:26 编辑

为什么我试了很多次就是不出来统一数字生产多次或消费多次的情况啊??是因为cpu是双核的缘故吗??
视频里说是会出问题的。。。。
朋友们看一下谢谢!

  1. public class Produce$CustomerDemo {

  2.         public static void main(String[] args) {
  3.                 Resource s = new Resource("烤鸭");
  4.                 Producer p = new Producer(s);
  5.                 Consumer c = new Consumer(s);
  6.         
  7.                 Thread t1 = new Thread(p);
  8.                 Thread t3 = new Thread(p);
  9.                 Thread t2 = new Thread(c);
  10.                 Thread t4 = new Thread(c);
  11.                 t1.start();
  12.                 t3.start();
  13.                 t2.start();
  14.                 t4.start();

  15.         }

  16. }

  17. class Resource {
  18.         String thing;

  19.         Resource(String thing) {
  20.                 this.thing = thing;
  21.         }

  22.         boolean flag = false;
  23.         int count = 1;

  24.         public void set() {
  25.                 while (true)
  26.                         synchronized (this) {
  27.                                 if (!flag) {
  28.                                         System.out.println(thing + ".....生产" + count);
  29.                                         flag = true;
  30.                                 }
  31.                         }

  32.         }

  33.         public void out() {
  34.                 while (true)
  35.                         synchronized (this) {
  36.                                 if (flag) {
  37.                                         System.out.println(thing + "..............消费" + count++);
  38.                                         flag = false;
  39.                                 }
  40.                         }
  41.         }

  42. }

  43. class Producer implements Runnable {
  44.         private Resource R;

  45.         Producer(Resource R) {
  46.                 this.R = R;
  47.         }

  48.         @Override
  49.         public void run() {
  50.                 R.set();

  51.         }

  52. }

  53. class Consumer implements Runnable {
  54.         private Resource R;

  55.         Consumer(Resource R) {
  56.                 this.R = R;
  57.         }

  58.         @Override
  59.         public void run() {
  60.                 R.out();

  61.         }

  62. }
复制代码
您需要登录后才可以回帖 登录 | 加入黑马