package cn.cast.day13;
public class DatebaseDemo {
public void main(String[] args) {
Database db = new Database();
new DBA(db).start();
new Developer(db).start();
}
}
class Database {
String name;
String gender;
boolean isUpdate;
}
class DBA extends Thread {
private Database db;
private int times;
public DBA(Database db) {
this.db = db;
}
public void run() {
while(true)
synchronized(db) {
if(db.isUpdate)
try {
db.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(times++ % 2 == 0) {
db.name = "宗";
db.gender = "男";
}else if(times++ % 2 == 1) {
db.name = "宋";
db.gender = "女";
}
db.isUpdate = true;
db.notify();
}
}
}
class Developer extends Thread {
private Database db;
public Developer(Database db) {
this.db = db;
}
public void run() {
while(true)
synchronized(db) {
if(db.isUpdate)
try {
db.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(db.name + db.gender);
db.isUpdate = false;
db.notify();
}
}
} |