スレッドは交互に実行され、1つの書き込み、1つの読み取りが行われます.

3679 ワード

import java.util.Stack;

public class SynchronizedTest {

    public static void main(String[] args) {
        Stack<String> s = new Stack<String>();
        Thread t1 = new Producer(s);
        t1.start();
        Thread t2 = new Consumer(s);
        t2.start();
    }

}

class Consumer extends Thread {

    Stack<String> s;

    public Consumer(Stack<String> s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (s) {
                while (s.empty()) {
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("pop:" + s.pop());
                s.notify();
            }
        }
    }

}

class Producer extends Thread {
    Stack<String> s;

    public Producer(Stack<String> s) {
        this.s = s;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (s) {
                while (!s.empty()) {
                    try {
                        s.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("push:" + s.push("a"));
                s.notify();
            }
        }
    }

}

出力:
push:a pop:a push:a pop:a
......
 
または、
import java.util.Stack;

public class SynchronizedTest {

    public static void main(String[] args) {
        Data data = new Data();
        Thread t1 = new Producer(data);
        t1.start();
        Thread t2 = new Consumer(data);
        t2.start();
    }

}

class Data {
    Stack<String> s = new Stack<String>();

    public synchronized void read() {
        while (s.empty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("pop:" + s.pop());
        notify();
    }

    public synchronized void write() {
        while (!s.empty()) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("push:" + s.push("a"));
        notify();
    }
}

class Consumer extends Thread {

    Data data;

    public Consumer(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        while (true) {
            data.read();
        }
    }

}

class Producer extends Thread {
    Data data;

    public Producer(Data data) {
        this.data = data;
    }

    @Override
    public void run() {
        while (true) {
            data.write();
        }
    }

}