共享资源是汽车Car,需要不断的打蜡waxed()和抛光buffed(),waxed()要等待buffed()完成,buffed()又要等待waxed()完成
<pre name="code" class="java">package com.test.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class WaxOMatic {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Car car=new Car();
ExecutorService exec=Executors.newCachedThreadPool();
exec.execute(new WaxOn(car));
exec.execute(new WaxOff(car));
TimeUnit.SECONDS.sleep(1);
System.out.println("trying to terminate all threads!!!!!");
exec.shutdownNow();
}
}
class Car{
private boolean waxOn=false;
public synchronized void waxed(){ //打蜡
System.out.println("waxOn!");
waxOn=true;
notifyAll();
}
public synchronized void buffed(){ //抛光
System.out.println("waxOff!");
waxOn=false;
notifyAll();
}
public synchronized void waitingForWaxing() throws InterruptedException{
while(false==waxOn){
System.out.println("waiting for Waxing!");
wait();
}
}
public synchronized void waitingForBufferring() throws InterruptedException{
while(true==waxOn){
System.out.println("waiting for Bufferring!");
wait();
}
}
}
class WaxOn implements Runnable{
private Car car;
public WaxOn(Car c){
car=c;
}
@Override
public void run(){
try{
while(!Thread.interrupted()){
car.waxed();
TimeUnit.MILLISECONDS.sleep(200);
car.waitingForBufferring();
}
}catch(InterruptedException e){
System.out.println("waxed interrupt exception");
}
System.out.println("waxed car end-------");
}
}
class WaxOff implements Runnable{
private Car car;
public WaxOff(Car c){
car=c;
}
@Override
public void run(){
try{
while(!Thread.interrupted()){
car.waitingForWaxing();
car.buffed();
TimeUnit.MILLISECONDS.sleep(200);
}
}catch(InterruptedException e){
System.out.println("buffed interrupt exception");
}
System.out.println("buffed car end-------");
}
}
输出:
waxOn!
waxOff!
waxOn!
waxOff!
waxOn!
waxOff!
waxOn!
waxOff!
waiting for Waxing!
waxOn!
waxOff!
trying to terminate all threads!!!!!
buffered car end-------
waxed car end-------
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]