package com.itheima;
public class Test11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Solt s=new Solt();
new Thread(new Tucker(s)).start();
new Thread(new Sonera(s)).start();
}
}
class Solt{
String name;
boolean f=false;
}
class Tucker implements Runnable{
private Solt s;
public Tucker(Solt s) {
super();
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(s){
if(s.f){
try {
s.wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
System.out.println("妈妈做饭,发现没有盐");
s.f=true;
s.notify();
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("妈妈继续做饭");
}
}
}
class Sonera implements Runnable{
private Solt s;
public Sonera(Solt s) {
super();
this.s = s;
}
public void run() {
// TODO Auto-generated method stub
synchronized(s){
if(!(s.f)){
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("儿子去买盐");
s.f=true;
s.notify();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("买盐回来");
s.notify();
}
}
}
自己写的,不知道哪里还有改进的。大家看看 |
|