- /*
- * 为什么运行一次后就卡死。
- */
- package cn.copy;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.ReentrantLock;
- public class DateBaseDemo {
- public static void main(String[] args) {
- DateBase db = new DateBase();
- new DBA(db).start();
- new Developer(db).start();
- }
- }
- class DateBase {
- String name;
- String sex;
- boolean Update;
- ReentrantLock lock = new ReentrantLock();
- Condition c1 = lock.newCondition();
- Condition c2 = lock.newCondition();
- }
- class DBA extends Thread {
- private DateBase db;
- private int times;
- public DBA(DateBase db) {
- this.db = db;
- }
- public void run() {
- while (true) {
- db.lock.lock();
- if (db.Update == true)
- try {
- db.c1.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if (times++ % 2 == 0) {
- db.name = "秦岩";
- db.sex = "男";
- } else {
- db.name = "晁喆";
- db.sex = "女";
- }
- db.Update = true;
- db.c2.signal();
- db.lock.unlock();
- }
- }
- }
- class Developer extends Thread {
- private DateBase db;
- public Developer(DateBase db) {
- this.db = db;
- }
- public void run() {
- db.lock.lock();
- if (db.Update == false)
- try {
- db.c2.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(db.name + ", " + db.sex);
- db.Update = false;
- db.c1.signal();
- db.lock.unlock();
- }
- }
复制代码 哪里错了吗? 我实在是找不到啊~~~ 帮帮忙~~ |