public class ValueObject {
public static String value = "";
}
//生产者
public class Product {
private String lock;
public Product(String lock) {
this.lock = lock;
}
public void setValue() {
try {
synchronized (lock) {
if(!ValueObject.value.equals("")) {
lock.wait();
}
String value = System.currentTimeMillis() + "_" + System.nanoTime();
System.out.println("set:" + value);
ValueObject.value = value;
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费者
public class Customer {
private String lock;
public Customer(String lock) {
this.lock = lock;
}
public void getValue() {
try {
synchronized (lock) {
if(ValueObject.value.equals("")) {
lock.wait();
}
System.out.println("get:" + ValueObject.value);
ValueObject.value = "";
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ThreadA extends Thread{
private Product product;
public ThreadA(Product product) {
this.product = product;
}
@Override
public void run() {
while (true) {
product.setValue();
}
}
}
public class ThreadB extends Thread {
private Customer customer;
public ThreadB(Customer customer) {
this.customer = customer;
}
@Override
public void run() {
while (true) {
customer.getValue();
}
}
}
public class Test {
public static void main(String[] args) {
try {
String lock = new String("");
Product product = new Product(lock);
ThreadA threadA = new ThreadA(product);
threadA.start();
Thread.sleep(1000);
Customer customer = new Customer(lock);
ThreadB threadB = new ThreadB(customer);
threadB.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
![](https://img.haomeiwen.com/i16792546/effeb76a9fc6b343.png)
image.png
网友评论