java多线程举例

生产者消费者===现成同步举例;

package lession.lession6;
import java.util.*;
//==========================模拟销售馒头的线程同步============================
/*
class Ham{
 public static Object box=new Object();
 public static   int material=6;  //有材料6个可以做6个 馒头
 public static   int sales=0;
 public static   int production=3;
}
class Hammaker extends Thread{
 private void Make(){
  synchronized(Ham.box){
   Ham.production++;
   int num=Ham.production-Ham.sales;
   System.out.println("<厨师>:这里有馒头"+num+"个,拿去卖");
   Ham.box.notify();   // 唤醒服务员线程 如果把这里注释的话,会让服务员线程一直等待了,
  }
 }
 public void run(){
  while(Ham.production<=Ham.material){
   try{
    sleep(3000);
   }catch(InterruptedException ie){}
   Make();    //没隔1秒做一个馒头
  }
 }
}
class HAssistant extends Thread{
 private void Sell(){
  synchronized(Ham.box){
   if(Ham.production==Ham.sales){
    System.out.println("<服务员>:请稍后,馒头马上就来。。。。。。");
    try{
     Ham.box.wait();
    }catch(InterruptedException ie){}
   }   
   int num=Ham.production-Ham.sales;
   Ham.sales++;
   System.out.println("<服务员>:顾客门,馒头来了哦,一共有"+num+"个");    
   
  }
 }
 public void run(){
  while(Ham.sales<=Ham.material){
   System.out.println("=============<顾客门来买馒头了>===========");
   Sell();
   try{
    sleep(1000);//每隔一秒就卖一个馒头
   }catch(InterruptedException ie){}
  }
 }
}
public class thread1{
 public static void main(String []args){
  Hammaker maker=new Hammaker();
  HAssistant assistant =new HAssistant();
  maker.start();
  assistant.start();
  try{
   maker.join();           //等待该线执行完毕
   assistant.join();
  }
  catch(InterruptedException ie){}
  System.out.println();
  System.out.println(Ham.sales+"/n"+Ham.production);
 }
}
/*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值