class Produce{
int num = 50;
private String name;
private int count = 0;
boolean flag = false;
private final Lock lock = new ReentrantLock();
final Condition pro = lock.newCondition();
final Condition con = lock.newCondition();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void putIn() throws InterruptedException{
while(getCount()<num){
lock.lock();
try {
Thread.sleep(50);
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
while(flag){
pro.await();
}
if(getCount()<num){
this.setName("生产者");
count++;
System.out.println(Thread.currentThread().getName()+"---"+name+"---"+count);
flag = true;
con.signal();
}
}
finally{
lock.unlock();
}
}
}
public void putOut() throws InterruptedException{
while(getCount()<=num){
lock.lock();
try {
Thread.sleep(50);
}
catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
while(!flag){
con.await();
}
if(getCount()<num){
this.setName("消费者");
System.out.println(Thread.currentThread().getName()+"----"+name+"----"+count);
//count++;
flag = false;
pro.signal();
}
//在这里我改变了条件,为什么还是不能自动停止呢???
else if(getCount()==num){
this.setName("消费者");
System.out.println(Thread.currentThread().getName()+"----"+name+"----"+count);
count++;
}
}
finally{
lock.unlock();
}
}
}
}
class Producer implements Runnable{
private Produce p;
Producer(Produce p){
this.p = p;
}
public void run(){
try {
p.putIn();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
private Produce p;
Consumer(Produce p){
this.p = p;
}
public void run(){
try {
p.putOut();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class LockTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Produce p = new Produce();
new Thread(new Producer(p)).start();
new Thread(new Producer(p)).start();
new Thread(new Consumer(p)).start();
new Thread(new Consumer(p)).start();
}