- class Resource {
- private String name;
- private int count = 1;
- private boolean flag = false;
- Lock lock = new ReentrantLock();
- Condition producer_con = lock.newCondition();// eclipse提示出故障,如果先敲Condition
- // producer_con=然后出提示
- Condition consumer_con = lock.newCondition();
- public void setName(String name) {//生产线
- lock.lock();
- try {
- while (flag) {
- try {
- producer_con.await();//生产等待
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- this.name = name + count;
- count++;
- System.out.println(Thread.currentThread().getName() + "生产者"
- + this.name);
- flag = true;
- consumer_con.signal();//唤醒消费
- } finally {
- lock.unlock();
- }
- }
- public void getName() {//消费线
- lock.lock();
- try {
- while (!flag) {
- try {
- consumer_con.await();//消费等待
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName()
- + "消费者------------" + this.name);
- flag = false;
- producer_con.signal();//唤醒生产
- } finally {
- lock.unlock();
- }
- }
- }
复制代码 |