当前位置: 代码迷 >> J2SE >> 线程有关问题,紧急求解!各位大侠们
  详细解决方案

线程有关问题,紧急求解!各位大侠们

热度:103   发布时间:2016-04-24 01:08:21.0
线程问题,紧急求解!!!各位大侠们
各位群里大侠能解决一个问题吗?? 线程问题 下面的代码,注释的那些行后为什么结果是随机数呢!!!!加上注释就正常了 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();
}
}
}
}


------解决方案--------------------
没有随机数啊。你不设置范围,变负数。不知道楼主啥问题
Java code
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();    }}
------解决方案--------------------
不是“从-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--”是非并发安全的,当然这是另一个话题。
  相关解决方案