本帖最后由 郝勇 于 2013-4-12 19:59 编辑
- *public class Test10 {
- public static void main(String[] args)
- {
- Salt s = new Salt();
- new Thread(new Mom(s)).start();
- new Thread(new Son(s)).start();
- }
- }
- class Salt{
- boolean flag = false;
- }
- class Mom implements Runnable
- {
- private Salt s;
- Mom(Salt s)
- {
- this.s = s;
- }
- public void run()
- {
- while(true){
- synchronized(s){
- if(s.flag){
- try{s.wait(1000);}
- catch(Exception e){}
- System.out.println("妈妈说:没盐了,儿子,买盐去!没法做饭了");
- s.flag = true;
- s.notify();
- }
- }
- }
- }
- }
- class Son implements Runnable{
- private Salt s;
- Son(Salt s)
- {
- this.s = s;
- }
- public void run()
- {
- while(true){
- synchronized(s){
- if(!s.flag)
- try{s.wait();}catch(Exception e){}
- System.out.println("好的,马上去买盐!!!");
- s.flag = false;
- s.notify();
- }
- }
- }
- }
复制代码 |
|