Java 멀티스레드 Wait() 및 Notify()

7126 단어 java 다중 루틴
1. Wait()와 Notify, NotifyAll은 모두 Object의 방법이다
2. 다중 스레드 협업은 동일한 객체를 제어하는 Wait()와 Notify()를 통해 수행됩니다.
3. Wait () 방법을 호출할 때, 현재 스레드는 다른 스레드가 대상의 Notify () 방법을 호출할 때까지 막힌 상태로 들어간다
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();
    }
}

좋은 웹페이지 즐겨찾기