class Res{
private boolean flag=false;
private String name;
private int bianhao=1;
public synchronized void set(String name){
while(flag){
try{
wait();
}
catch(Exception e){
}
this.name=name+"......"+bianhao++;
System.out.println(Thread.currentThread().getName()+"......"+this.name);
flag=true;
this.notifyAll();
}
}
public synchronized void out(){
while(!flag){
try{
wait();
}
catch(Exception e){
}
System.out.println("consume:"+name+"........."+bianhao++);
flag=false;
this.notifyAll();
}
}
}
class Produce implements Runnable{
Res r;
Produce(Res r){
this.r=r;
}
public void run(){
while(true)
r.set("商品");
}
}
class Sale implements Runnable{
Res r;
Sale(Res r){
this.r=r;
}
public void run(){
while(true)
r.out();
}
}
public class lx {
public static void main(String[] args){
Res r=new Res();
Produce pr=new Produce(r);
Sale sal=new Sale(r);
Thread t1=new Thread(pr);
Thread t2=new Thread(pr);
Thread t3=new Thread(sal);
Thread t4=new Thread(sal);
t1.start();
t2.start();
t3.start();
t4.start();
}
}哪里出错了找了好久实在不懂 求高手帮忙看看 万分感谢!!!!!!!! 另外这个代码中produce和sale中创建的Res r后 用加了一个构造方法用来传递Res对象 但是在这个代码中不构建我感觉也没影响吧,给我分析下 谢谢
------解决方案--------------------
class Res {
private boolean flag = false;
private String name;
private int bianhao = 1;
public synchronized void set(String name) {
while (flag) {
try {
wait();
} catch (Exception e) {
}
this.name = name + "......" + bianhao++;
System.out.println(Thread.currentThread().getName() + "......"
+ this.name);
flag = true;
this.notifyAll();
}
}
public synchronized void out() {
while (!flag) {
try {
wait();
} catch (Exception e) {
}
System.out.println("consume:" + name + "........." + bianhao++);
flag = false;
this.notifyAll();
}
}
}
class Produce implements Runnable {
Res r;
Produce(Res r) {
this.r = r;
}
public void run() {
while (true)
r.set("商品");
}
}
class Sale implements Runnable {
Res r;
Sale(Res r) {
this.r = r;
}
public void run() {
while (true)
r.out();
}
}
class lx {
public static void main(String[] args) {
Res r = new Res();
Produce pr = new Produce(r);
Sale sal = new Sale(r);
Thread t1 = new Thread(pr);
Thread t2 = new Thread(pr);
Thread t3 = new Thread(sal);
Thread t4 = new Thread(sal);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
------解决方案--------------------
3.纠正下:因为flag的初始状态为flase,你在set()中用while(flag)来判断的话,while中代码始终得不到执行,flag也就始终为false!所以当你在out()方法中进入while循环之后,调用wait()阻塞的那些线程永远不会被唤醒,你的程序肯定运行不起来!
当然你这里用while来判断flag貌似也行,但是你也需要将try{}catch{}后面的代码拿到while循环外面来