- 当使用线程来同时运行多个任务时,可以通过使用锁(互斥)来同步两个任务的行为,从而使得一个任务不会干涉另一个任务的资源。也就是说,如果两个任务在交替着不如某项共享资源(通常是内存),可以使用互斥来使得任何时刻只有一个任务可以访问这项资源。
wait()与notify()
- wait()提供了一种在任务之间对活动同步的方式。
- 在wait()期间对象锁是释放的。
- 可以通过notify()、notifyAll(),或者令时间到期,从wait()中恢复执行。
- 如果在非同步控制方法里调用wait(),notify(),notifyAll(),程序能通过编译,但运行的时候,将得到IllegalMonitorStateException异常。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by Panda on 2018/6/5.
*/
class Car{
private boolean waxOn=false;
public synchronized void waxed(){
waxOn=true;
notifyAll();
}
public synchronized void buffed(){
waxOn=false;
notifyAll();
}
public synchronized void waitForWaxing() throws InterruptedException{
while (waxOn==false)
wait();
}
public synchronized void waitForBuffing() throws InterruptedException{
while (waxOn==true)
wait();
}
}
class WaxOn implements Runnable{
private Car car;
public WaxOn(Car car) {
this.car = car;
}
@Override
public void run() {
try{
while (!Thread.interrupted()){
System.out.println("Wax on");
TimeUnit.MILLISECONDS.sleep(200);
car.waxed();
car.waitForBuffing();
}
}catch (InterruptedException e){
System.out.println("Exiting via interrupt");
}
System.out.println("Ending Wax On task");
}
}
class WaxOff implements Runnable{
private Car car;
public WaxOff(Car car) {
this.car = car;
}
@Override
public void run() {
try{
while (!Thread.interrupted()) {
car.waitForWaxing();
System.out.println("Wax off!");
TimeUnit.MILLISECONDS.sleep(20);
car.buffed();
}
}catch (InterruptedException e){
System.out.println("Exiting via interrupt");
}
System.out.println("Ending Wax Off task");
}
}
public class WaxOMatic {
public static void main(String[] args) throws Exception {
Car car = new Car();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new WaxOff(car));
executorService.execute(new WaxOn(car));
TimeUnit.SECONDS.sleep(5);
executorService.shutdownNow();
}
}