1+ package com .xforg .concurrency .com .xforg ;
2+ import java .util .concurrent .ExecutorService ;
3+ import java .util .concurrent .Executors ;
4+ import java .util .concurrent .TimeUnit ;
5+
6+ /**
7+ * Created by Administrator on 2016/5/5.
8+ */
9+ class Car {
10+ private boolean waxOn = false ;
11+ public synchronized void waxed (){
12+ waxOn = true ;
13+ notifyAll ();
14+ }
15+ public synchronized void buffed () throws InterruptedException {
16+ while (waxOn == false )
17+ wait ();
18+ }
19+ public synchronized void waitForWaxing () throws InterruptedException {
20+ while (waxOn == true )
21+ wait ();/*如果waxOn为true。那么这个调用任务将通过调用wait而被挂起,此时线程被挂起,锁被释放*/
22+ }
23+ public synchronized void waitForBuffing () throws InterruptedException {
24+ while (waxOn == true )
25+ wait ();
26+ }
27+ }
28+ class WaxOn implements Runnable {
29+ private Car car ;
30+ public WaxOn (Car c ){
31+ car = c ;
32+ }
33+
34+ @ Override
35+ public void run () {
36+ try {
37+ while (! Thread .interrupted ()){
38+ System .out .println ("Wax On !" );
39+ TimeUnit .MILLISECONDS .sleep (200 );
40+ car .waxed ();
41+ car .waitForBuffing ();
42+ }
43+ }catch (InterruptedException e ){
44+ System .out .println ("Exiting via interrupt" );
45+ }
46+ System .out .println ("Ending Wax on task" );
47+ }
48+ }
49+ class WaxOff implements Runnable {
50+ private Car car ;
51+ public WaxOff (Car c ){
52+ car = c ;
53+ }
54+
55+ @ Override
56+ public void run () {
57+ try {
58+ while (! Thread .interrupted ()){
59+ car .waitForWaxing ();
60+ System .out .println ("Wax Off" );
61+ TimeUnit .MILLISECONDS .sleep (200 );
62+ car .buffed ();
63+ }
64+ }catch (InterruptedException e ){
65+ System .out .println ("Exiting via interrupt" );
66+ }
67+ System .out .println ("EndingWax off task" );
68+ }
69+ }
70+ public class WaxOMatic {
71+ public static void main (String [] args ) throws Exception {
72+ Car car = new Car ();
73+ ExecutorService exec = Executors .newCachedThreadPool ();
74+ exec .execute (new WaxOff (car ));
75+ exec .execute (new WaxOn (car ));
76+ TimeUnit .SECONDS .sleep (5 );
77+ exec .shutdown ();
78+ }
79+ }
0 commit comments