package day1;
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) {
Lockc ck = new Lockc();
producer p = new producer (ck);
consumer c= new consumer(ck);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Lockc{
private String name;
public int cuu=1;
private boolean o = false;
Lock kk = new ReentrantLock();
Condition ll_1 = kk.newCondition();
Condition ll_2 = kk.newCondition();
public void set(String name) throws InterruptedException{
kk.lock();
while(o)
try {
ll_1.await(); //t1 t2
this.name=name+"....."+cuu++;
System.out.println("生产者...................."+this.name+"..........");
o=true;
ll_2.signal();
}finally{
kk.unlock();
}
}
public void out() throws InterruptedException{
kk.lock();
while(!o)
try {
ll_2.await(); //t3 t4
System.out.println("消费者"+"...........");
o = false;
ll_1.signal();
} finally{
kk.unlock();
}
}
}
class producer implements Runnable{
private Lockc lo;
producer (Lockc lo){
this.lo = lo;
}
@Override
public void run() {
while(true){
// if(lo.cuu>0)
try {
lo.set("++商品++");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class consumer implements Runnable{
private Lockc lo;
consumer(Lockc lo){
this.lo = lo;
}
@Override
public void run() {
while(true){
try {
lo.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
为什么while(o)在try外面,能启动线程,而不执行代码,
当我把whiile(o)拿到try{}里面, 如: try{
while(o)
}
就能正常的运行代码, 真分不清这两种有什么不同,希望高手来解答。
|