sinat_34458693
sinat_34458693
2016-03-29 07:10

java se 多线程资源共享问题

  • java
  • 线程
  • 多线程
class bread{
    int num = 0;

    public synchronized void makeBreand(){
            num++;
            this.notify();      

    }

    public synchronized void sale(){
        while(num==0){
            try{
                this.wait();
                System.out.println("暂时无面包,等待");
            }catch(InterruptedException e){e.printStackTrace();}

        }
        num--;

    }
}

class makeThread implements Runnable{
bread account;

public makeThread(bread s){
    account = s;

}
public void run(){
while(account.num<10){
    account.makeBreand();
    System.out.println(Thread.currentThread().getName()+"thread is working");
    System.out.println("面包数量+1,已有"+account.num+"个面包");
    try{
        Thread.sleep(1000);
    }catch(InterruptedException e){e.printStackTrace();}
}
    }

}

class saleThread implements Runnable{
bread left;
public saleThread(bread s){
left = s;
}
public void run(){
if(left.num>0){
left.sale();
System.out.println(Thread.currentThread().getName()+"售出面包一个");
System.out.println("目前有"+left.num+"个面包");
try{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}
}
}
}

public class test{
public static void main(String[] args){
bread b = new bread();

    saleThread sale = new saleThread(b);
    makeThread make = new makeThread(b);
    Thread t1 = new Thread(make);
    Thread t2 = new Thread(sale);
    t1.start();
    t2.start();
}

}

代码如下,运行效果:
Thread-1售出面包一个
Thread-0thread is working
目前有0个面包
面包数量+1,已有0个面包
Thread-0thread is working
面包数量+1,已有1个面包
Thread-0thread is working
面包数量+1,已有2个面包
Thread-0thread is working
面包数量+1,已有3个面包
Thread-0thread is working
面包数量+1,已有4个面包
Thread-0thread is working
面包数量+1,已有5个面包
Thread-0thread is working
面包数量+1,已有6个面包
Thread-0thread is working
面包数量+1,已有7个面包
Thread-0thread is working
面包数量+1,已有8个面包
Thread-0thread is working
面包数量+1,已有9个面包
Thread-0thread is working
面包数量+1,已有10个面包

为什么我的sale进程只被调用了一次?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答

为你推荐