生产者与消费者

数据

public class Data
{

/** 集合 **/
private static HashMap<String, String> table = new HashMap<String, String>();


/**
* 保存
*/
public void put()
{
synchronized (table)
{
if(size() == 0)
{
String key = new Random().nextInt() + "";
String value = new Random().nextInt() + "";
table.put(key, value);
System.out.println("~~~生产:" + key);
}
}
}
/**
* 删除
*/
public void remove()
{
synchronized (table)
{
String key = getKey();
if(key != null)
{
table.remove(key);
System.out.println("消费:" + key);
}
}
}

/**
* 得到某一个key值
* @return
*/
public String getKey()
{
Set<String> keySet = table.keySet();
Iterator<String> keyIt = keySet.iterator();
while(keyIt.hasNext())
{
return keyIt.next();
}
return null;
}

/**
* 长度
* @return
*/
public int size()
{
return table.size();
}
}


生产者

public class MakeThread implements Runnable
{
/** 开关 **/
private boolean isRun = true;

Data data = new Data();

@Override
public void run()
{

while(isRun)
{
try
{
Thread.sleep(20);

}
catch (InterruptedException e)
{e.printStackTrace();}

data.put();
}
}
}


消费者

public class UseThread implements Runnable
{
/** 开关 **/
private boolean isRun = true;

//数据
Data data = new Data();

@Override
public void run()
{

while(isRun)
{
try
{
Thread.sleep(10);

}
catch (InterruptedException e)
{e.printStackTrace();}

data.remove();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值