一:使用多线程,存入一个数据就取出一个数据,wait(),notify()机制
class InputOutputDemo {
public static void main(String[] args) {
Person p = new Person();
Thread threadInput = new Thread(new InputRunnable(p)); //生产数据的线程
Thread threadOutput = new Thread(new OutputRunnable(p)); //消费数据的线程
threadInput.start();
threadOutput.start();
}
}
class InputRunnable implements Runnable {
public Person p;
InputRunnable(Person p) {
this.p=p;
}
public void run() {
int x = 0;
while(true) {
synchronized(p) {
if(p.valid) { //判断是否已生产
try {
p.wait(); //如果已生产则让线程等待
} catch(Exception e) {}
}
if(x==0) {
p.name = "涂勇";
p.sex = "男";
} else