- package org.yang;
- public class Test
- {
- public static void main(String[] args)
- {
- final Businese b = new Businese();
- new Thread(new Runnable() {
- public void run()
- {
- while (true)
- {
- b.sub();
- }
- }
- }).start();
- new Thread(new Runnable() {
- public void run()
- {
- while (true)
- {
- b.main();
- }
- }
- }).start();
- }
- }
- class Businese
- {
- boolean isSubRun = true;
- public synchronized void sub()
- {
- while ( !isSubRun )
- {
- try
- {
- this.wait();
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("老人说轮到孩子走了");
- System.out.println("孩子走呀走..........");
- this.isSubRun = false;
- this.notify();
- }
- public synchronized void main()
- {
- while ( isSubRun )
- {
- try
- {
- this.wait();
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("孩子说轮到老人走了:");
- System.out.println("老人走呀走.........");
- this.isSubRun = true;
- this.notify();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/170320149055.html
来源: http://www.codesnippet.cn/detail/170320149055.html