各位群里大侠能解决一个问题吗?? 线程问题                       下面的代码,注释的那些行后为什么结果是随机数呢!!!!加上注释就正常了                                                                                                                                                                                                                                                                                                             public static void main(String[] args) {
    Table table = new Table();
    Person p1 = table.new Person();
    Person p2 = table.new Person();
    p1.start();
    p2.start();
  }
}
class Table{
   int beans = 20;
  public  int getBean(){
//       if(beans==0)
//         throw new RuntimeException("没了!");
//       try {
//         Thread.sleep(10);
//       } catch (InterruptedException e) {
//         e.printStackTrace();
//       }
      return beans--;
   
  }
  class Person extends Thread{
    public void run(){
      while(true){
        int bean = getBean();
        System.out.println(getName()+"吃了"+bean);
        Thread.yield();
      }
    }
  }
}

解决方案 »

  1.   

    没有随机数啊。你不设置范围,变负数。不知道楼主啥问题public class Table {
    int beans = 20;
    public synchronized int getBean(){//加同步锁住beans
    if (beans == 0){
    throw new RuntimeException("没了!");
    }
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return beans--;
    }
    class Person extends Thread {
    public void run() {
    while (true) {
    int bean = getBean();
    System.out.println(this.getName() + "吃了" + bean);
    Thread.yield();
    }
    }
    }
    public static void main(String[] args) {
    Table table = new Table();
    Person p1 = table.new Person();
    Person p2 = table.new Person();
    p1.start();
    p2.start();
    }
    }
      

  2.   

    嗯 出来的本来的就是负数!!!加了同步锁也是一样的!!!!我的代码里面beans=20;但是它运行出来的时候,就不是从20开始往下面减的,而是从-45465165,一个很大的负数开始........
      

  3.   

    不是“从-45465165,一个很大的负数开始”而是因为速度太快,一下子就刷屏把前面刷没了吧。
    你把:
    while (true) {
       int bean = getBean();
       System.out.println(getName() + "吃了" + bean);
       Thread.yield();
    }修改为:
    for (int i = 0;i < 50; i++) { // 控制下循环规模,不要无限制循环
       int bean = getBean();
       System.out.println(getName() + "吃了" + bean);
       Thread.yield();
    }
    不过你这个程序本身“beans--”是非并发安全的,当然这是另一个话题。