package com.sky.thread1;
class Product {
int n;
boolean valueSet = false;
synchronized void get() {
if (!valueSet) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "-get-" + n);
valueSet = false;
notify();
}
synchronized void put(int n) {
if (valueSet) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
this.n = n;
valueSet = true;
System.out.println(Thread.currentThread().getName() + "-put-" + n);
notify();
}
}
class Producer implements Runnable{
Product product;
public Producer(Product product) {
this.product = product;
new Thread(this,"Producer").start();
}
@Override
public void run() {
int k = 0;
for (int i = 0; i < 5; i++) {
product.put(k++);
}
}
}
class Consumer implements Runnable {
Product product;
public Consumer(Product product) {
this.product = product;
new Thread(this,"Consumer").start();
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
product.get();
}
}
}
public class WaitDemo {
public static void main(String[] args) {
Product product = new Product();
Producer producer = new Producer(product);
Consumer consumer = new Consumer(product);
}
}
java线程间通讯
最新推荐文章于 2024-08-30 21:45:00 发布