码迷,mamicode.com
首页 > 其他好文 > 详细

汽车辐射监测系统-Qt开发[转]发

时间:2014-05-30 00:22:01      阅读:313      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

1.Wait()和Notify、NotifyAll都是Object的方法

2.多线程的协作是通过控制同一个对象的Wait()和Notify()完成

3.当调用Wait()方法时,当前线程进入阻塞状态,直到有另一线程调用了该对象的Notify()方法

bubuko.com,布布扣
package Thread.Wait;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

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 c) {
        car = c;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("Wax On!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();//上完蜡  waxOn = true;notifyAll();
                car.waitForBuffing();//等待抛光while (waxOn == true) wait();
            }
        } catch (Exception e) {
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax On task");
    }
}

class WaxOff implements Runnable {
    private Car car;

    public WaxOff(Car c) {
        car = c;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                car.waitForWaxing();//等待上蜡   while (waxOn == false) wait();
                System.out.println("Wax Off!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();//已经抛光  waxOn = false;    notifyAll();
            }
        } catch (Exception 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 exec = Executors.newCachedThreadPool();
        exec.execute(new WaxOff(car));
        exec.execute(new WaxOn(car));
        TimeUnit.SECONDS.sleep(5);
        exec.shutdownNow();
    }
}
bubuko.com,布布扣

 

汽车辐射监测系统-Qt开发[转]发,布布扣,bubuko.com

汽车辐射监测系统-Qt开发[转]发

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/lvdongjie/p/3757992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!