class Rec
{
private String name;
private String user;
private boolean flag;
private int count=100;
private final ReentrantLock lock=new ReentrantLock();
private Condition condition_input=lock.newCondition();
private Condition condition_output=lock.newCondition();
private Rec rec(){}
private static Rec rec=null;
public static Rec getInstance()
{
if (rec==null)
{
synchronized(Rec.class)
{
if (rec==null)
{
rec=new Rec();
}
}
}
return rec;
}
public void input(String name,String user)
{
lock.lock();
try
{
while (flag)
{
try
{
condition_input.await();
}
catch (Exception e)
{
}
if (count>0)
{
this.name=name;
this.user=user;
System.out.println(Thread.currentThread().getName()+"...公司:"+name+"...用户..."+user+"..."+"已存入数据库...还有"+count+"客户需要存储");
flag=true;
condition_output.signalAll();
}
else
{
System.out.println("数据库已经存满了,如果需要扩容,请再交钱!");
System.exit(0);
}
}
}
finally
{
lock.unlock();
}
}
public void output()
{
lock.lock();
try
{
while (!flag)
{
try
{
condition_output.await();
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"..获得的数据是...公司:" +name + "用户:"+ user+"里面还有"+count--+"个用户");
flag=false;
condition_input.signal();
}
}
finally
{
lock.unlock();
}
}
}
class Input implements Runnable
{
private Rec r;
Input(Rec r)
{
this.r=r;
}
public void run()
{
int x=0;
while (true)
{
try
{
Thread.sleep(20);
}
catch (Exception e)
{
}
if (x==0)
{
r.input("CSDN社区","狼行天下");
}
else
r.input("黑马程序员","jeromechen");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Rec r;
Output(Rec r)
{
this.r=r;
}
public void run()
{
while (true)
{
try
{
Thread.sleep(20);
}
catch (Exception e)
{
}
r.output();
}
}
}
class InputOutputTest2
{
public static void main(String[] args)
{
Rec r=Rec.getInstance();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
我用的是最新的JDK8.0,打开API里面有这些功能,但是不清楚为什么编译的时候总是说找不到和Lock相关的符号。1.8对应API:http://docs.oracle.com/javase/8/docs/api/index.html
D:AFQI$7X%5BS0NUPG)V)C9OE%9.png |