线程之间的交互通讯可以通过生产者消费者方式解决。
生产者: 负责生产数据
消费者:负责消费数据
缓冲区:消费者从缓冲区中消费数据,如果没有就等待阻塞,生产生产数据往缓冲区,缓冲区满了则阻塞等待消费者消费。
package thread;
/**
* 生产者消费者-- 管程法
*/
public class TestPC {
public static void main(String[] args) {
Container synContainer = new Container();
Producer producer = new Producer(synContainer);
Consumer comsumer = new Consumer(synContainer);
Thread p = new Thread(producer, "producer");
Thread c = new Thread(comsumer, "comsumer");
p.start();
c.start();
}
}
class Prodect {
private int id;
private String name;
public Prodect(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;
}
}
class Container {
Prodect[] prodects = new Prodect[10];
int count = 0;
public synchronized void produce(Prodect prodect) {
if (count == prodects.length) {
try {
System.out.println(Thread.currentThread().getName() + "生产者生产了产品未消费,阻塞等待!");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.prodects[count] = prodect;
count++;
this.notifyAll();
}
public synchronized Prodect comsumer() {
if (count == 0) {
try {
System.out.println(Thread.currentThread().getName() + "消费者没有产品消费,等待阻塞!");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Prodect prodect = this.prodects[count];
this.notifyAll();
return prodect;
}
}
class Producer implements Runnable {
private Container container;
public Producer(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.produce(new Prodect(i, "产品:" + i));
System.out.println(Thread.currentThread().getName() + "生产者生产了产品");
}
}
}
class Consumer implements Runnable {
private Container container;
public Consumer(Container container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Prodect prodect = container.comsumer();
System.out.println(Thread.currentThread().getName() + "消费者消费了产品 : " + prodect.getName());
}
}
}