一個生產者和一個消費者

1:建立數據存儲對象代碼以下java

public class ValueObject {
    public static String value = "";
}

2:建立生產者代碼以下ide

public class Produce {
    private String lock;
    public Produce(String lock) {
        this.lock = lock;
    }

    public void setValue() {
        try {
            synchronized (this.lock) {
                if (!ValueObject.value.equals("")) {
                    lock.wait();
                }
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                System.out.println("set的值是: " + value);
                ValueObject.value = value;
                this.lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3:建立消費者代碼以下測試

public class Consumer {
    private String lock;
    public Consumer(String lock) {
        this.lock = lock;
    }

    public void getValue() {
        try {
            synchronized (this.lock) {
                if (ValueObject.value.equals("")) {
                    lock.wait();
                }
                System.out.println("get的值是: " + ValueObject.value);
                ValueObject.value = "";
                this.lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

4:建立生產者線程代碼以下this

public class ThreadProduce extends Thread {
    private Produce produce;
    public  ThreadProduce(Produce produce) {
        this.produce = produce;
    }

    @Override
    public void run() {
        while (true) {
            produce.setValue();
        }
    }
}

5:建立消費者線程代碼以下線程

public class ThreadConsumer extends Thread {
    private Consumer consumer;
    public ThreadConsumer(Consumer consumer) {
        this.consumer = consumer;
    }

    @Override
    public void run() {
        while (true) {
            consumer.getValue();
        }
    }
}

6:建立測試類代碼以下code

public class Test {
    public static void main(String[] args) {
        String lock = new String ("");
        Produce produce = new Produce(lock);
        Consumer consumer = new Consumer(lock);

        ThreadProduce threadProduce = new ThreadProduce(produce);
        threadProduce.start();

        ThreadConsumer threadConsumer = new ThreadConsumer(consumer);
        threadConsumer.start();


    }
}
相關文章
相關標籤/搜索