package thread.myPAC;
public class Product {
private int id;
private String name;
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '''+'}';
}
}
package thread.myPAC;
public class Storage {Product[] products = new Product[10];
int top = 0;
public synchronized void push(Product product) throws InterruptedException {while (top == products.length) {System.out.println("仓库已满");
wait();}
products[top++]=product;
System.out.println(Thread.currentThread().getName() + "生产产品" + product);
notifyAll();}
public synchronized Product pop() throws InterruptedException {while (top == 0) {
try {System.out.println("仓库已空");
wait();} catch (InterruptedException e) {e.printStackTrace();
}
}
--top;
Product p = new Product(products[top].getId(), products[top].getName());
products[top] = null;
System.out.println(Thread.currentThread().getName() + "取出产品" + p);
notifyAll();
return p;
}
}
package thread.myPAC;
public class Producer implements Runnable {
private Storage storage;
public Producer(Storage storage) {this.storage = storage;}
@Override
public void run() {for (int i = 0; i < 10; i++) {
try {storage.push(new Product(i, "product" + i));
} catch (InterruptedException e) {e.printStackTrace();
}
}
}
}
package thread.myPAC;
public class Consumer implements Runnable {
private Storage storage;
public Consumer(Storage storage) {this.storage = storage;}
@Override
public void run() {for (int i = 0; i < 10; i++) {
try {storage.pop();
Thread.sleep(100);
} catch (InterruptedException e) {e.printStackTrace();
}
}
}
}
package thread.myPAC;
public class PACTest {public static void main(String[] args) throws InterruptedException {Storage storage = new Storage();
Thread consumer1 = new Thread(new Consumer(storage));
consumer1.setName("消费者 1");
Thread consumer2 = new Thread(new Consumer(storage));
consumer2.setName("消费者 2");
Thread producer1 = new Thread(new Producer(storage));
producer1.setName("生产者 1");
Thread producer2 = new Thread(new Producer(storage));
producer2.setName("生产者 2");
producer1.start();
producer2.start();
Thread.sleep(1000);
consumer1.start();
consumer2.start();}
}
- 同类线程通信,如果继承 Thread,要应用动态变量进行通信;如果实现 runnable 接口,成员变量就能够通信。
- 不同类线程通信,要在上一层进行配置。如 mian 中的 Storage 被生产者和消费者共用。