您的位置:首页 > 其它

LockDemo

2014-02-04 15:19 281 查看
package cn.sice;

import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo
{

public static void main(String[] args)
{
Res r = new Res();
In in = new In(r);
Out out = new Out(r);
new Thread(in).start();
new Thread(out).start();
}

}

class Res
{
ArrayList<String> arrList = new ArrayList();
Lock lock = new ReentrantLock();
Condition conSet = lock.newCondition();
Condition conGet = lock.newCondition();
boolean flag = false;

public void set()
{
lock.lock();
try
{
while (flag)
conSet.await();

arrList.add(new Date().toString());
System.out.println("SET----" + arrList.size() + "-- "
+ arrList.get(arrList.size() - 1) + "  ***  "
+ Thread.currentThread().getName());
flag = true;
conGet.signal();

} catch (InterruptedException e)
{
e.printStackTrace();
} finally
{
lock.unlock();
}

}

public void get()
{
lock.lock();
try
{
while (!flag)
conGet.await();
System.out.println("GET----" + arrList.size() + "-----"
+ arrList.get(0) + "  ***  "
+ Thread.currentThread().getName());
arrList.remove(0);
flag = false;
conSet.signal();
} catch (InterruptedException e)
{
e.printStackTrace();
} finally
{
lock.unlock();
}
}
}

class In implements Runnable
{
public void run()
{
while (true)
{
r.set();
}
}

private Res r;

public In(Res r)
{
this.r = r;
}
}

class Out implements Runnable
{
private Res r;

public Out(Res r)
{
this.r = r;
}

public void run()
{
while (true)
{
r.get();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: