学习JAVA线程同步的一个小例子

package syn;

public class SyncThreadEx03 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SyncThreadEx03 st = new SyncThreadEx03();
//关于这种实例化的方式吗,我也不太明白 句柄?
Product p = st.new Product();
Customer c = st.new Customer();
Thread tp = new Thread(p,"product:");
Thread tc = new Thread(c,"customer");
//设置一下优先级 便于观察生产与卖出的数据变化
//如果默认的话 有可能会重复出现1010101010。。。
tp.setPriority(10);
tc.setPriority(7);
tp.start();
tc.start();
}
Iphone_Store is =new Iphone_Store();
class Product implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
//for(int i =0 ; i<is.max_num;i++){
// is.product();
//}
while(true){
is.product();
}
}

}
class Customer implements Runnable{

@Override
public void run() {
// TODO Auto-generated method stub
//for(int i = is.max_num ; i>is.min_num;i--){
// is.sale();
//}
while(true){
is.sale();
}
}

}
//表示 仓库
class Iphone_Store{
private int max_num = 10; //最大库存
private int min_num = 0; //最小库存
private int num=0; //现有量

//生产
public void product(){
synchronized(this){
try{
//当现有量 等于 最大库存的时候 生产线程等待,同时释放该仓库的锁
if(num == max_num){

this.wait();
//this.notify();
}
this.notify();
num++;
Thread.currentThread();
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() +": Iphone: "+ num);
}catch(Exception e){
e.printStackTrace();
}
}

}
//卖出
public void sale(){
synchronized(this){
try{
if(num == min_num){
wait();
//this.notify();
}
notify();
num--;
Thread.currentThread();
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+": Iphone: "+num);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值