public class Test1 {
public static void main(String[] args) {
Student s = new Student();
Get G = new Get(s);
Set S = new Set(s);
Thread t1 = new Thread(G);
Thread t2 = new Thread(S);
t2.start();
t1.start();
}
}
public class Student {
private String name;
private int age;
private boolean flag;
public synchronized void set (String name ,int age){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name=name;
this.age=age;
this.flag=true;
this.notify();
}
public synchronized void get(){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name+this.age+"个");
this.flag=false;
this.notify();
}
}
public class Set implements Runnable {
Student s;
public Set(Student s) {
this.s = s;
}
@Override
public void run() {
int i = 0;
while (true) {
if (i%2==0){
s.set("生产包子中,没有了:",0);
}else{
s.set("卖包子咯 还有:", 10);
}
i++;
}
}
}
public class Get implements Runnable {
private Student s;
public Get(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
} |
|