黑马程序员技术交流社区
标题:
Lock和Condition
[打印本页]
作者:
iceknc
时间:
2015-9-21 22:24
标题:
Lock和Condition
import java.util.concurrent.locks.*;
public class Goods {
private String name;
private int count = 0;
private boolean flag = false;
//定义一个锁
private final Lock lock = new ReentrantLock();
//定义生产者持的锁
private final Condition conditionPro = lock.newCondition();
//定义消费者持的锁
private final Condition conditionCon = lock.newCondition();
public void in(String name) throws InterruptedException {
lock.lock();
try{
while(flag)
conditionPro.await();
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + " 生产 " + this.name);
flag = true;
复制代码
public class Producer implements Runnable {
private Goods g;
public Producer(){}
public Producer(Goods g) {
this.g = g;
}
public void run(){
while(true){
try{
g.in("#商品#");
}
catch(InterruptedException e){
}
}
}
}
复制代码
public class Consumer implements Runnable{
private Goods g;
public Consumer(){}
public Consumer(Goods g) {
this.g = g;
}
public void run(){
while(true){
try{
g.out();
}
catch(InterruptedException e){
}
}
}
}
复制代码
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Goods g = new Goods();
Producer p = new Producer(g);
Consumer c = new Consumer(g);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).start();
}
}
复制代码
重要的代码写三遍,今天终于可以自己背着写出来了。
作者:
iceknc
时间:
2015-9-21 22:26
import java.util.concurrent.locks.*;
public class Goods {
private String name;
private int count = 0;
private boolean flag = false;
//定义一个锁
private final Lock lock = new ReentrantLock();
//定义生存者持的锁
private final Condition conditionPro = lock.newCondition();
//定义消费者持的锁
private final Condition conditionCon = lock.newCondition();
public void in(String name) throws InterruptedException {
lock.lock();
try{
while(flag)
conditionPro.await();
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName() + " 生产 " + this.name);
flag = true;
conditionCon.signal();
}
finally{
lock.unlock();
}
}
public void out()throws InterruptedException {
lock.lock();
try{
while(!flag)
conditionCon.await();
System.out.println(Thread.currentThread().getName() + " ...消费 " + this.name);
flag = false;
conditionPro.signal();
}
finally{
lock.unlock();
}
}
}
复制代码
复制漏了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2