黑马程序员技术交流社区
标题:
DAY_12
[打印本页]
作者:
三土
时间:
2015-7-25 20:27
标题:
DAY_12
package com.itheima1;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class tongxin {
public static void main(String[] args) {
Resouce r = new Resouce();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
class Resouce {
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_input = lock.newCondition();
private Condition condition_output = lock.newCondition();
public void set(String name) {
lock.lock();
try {
while (flag) {
condition_input.await();
}
this.name = name + count++;
System.out.println(Thread.currentThread().getName()
+ "...生产者......" + this.name);
flag = true;
condition_output.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.unlock();
}
}
public synchronized void out() {
lock.lock();
try {
while (!flag) {
condition_output.await();
}
System.out.println(Thread.currentThread().getName() + "+消费者+"
+ this.name);
flag = false;
condition_input.signal();
} catch (Exception e) {
// throw new RuntimeException();
} finally {
lock.unlock();
}
}
}
class Producer implements Runnable {
private Resouce r;
Producer(Resouce r) {
this.r = r;
}
public void run() {
while (true) {
r.set("汉堡");
}
}
}
class Consumer implements Runnable {
private Resouce r;
Consumer(Resouce r) {
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
复制代码
作者:
大鹏37
时间:
2015-7-25 20:43
入学十二天了吗,感觉怎么样啊
作者:
三土
时间:
2015-7-25 21:11
大鹏37 发表于 2015-7-25 20:43
入学十二天了吗,感觉怎么样啊
在家里看视频哦! 复习一遍
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2