import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Store {
private int count;
private final int SIZE;
private JFrame frame = new JFrame();
private JTextField[] fields = new JTextField[2];
public Store(int size) {
this.SIZE = size;
Producer producer = new Producer(this);
Consumer consumer = new Consumer(this);
producer.setName("生成了");
consumer.setName("消费了");
fields[0] = new JTextField();
fields[1] = new JTextField();
frame.add(fields[0], BorderLayout.NORTH);
frame.add(fields[1], BorderLayout.SOUTH);
producer.start();
consumer.start();
frame.pack();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void addData() {
synchronized (this) {
while (count == SIZE) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fields[0].setText(Thread.currentThread().getName() + ++count
+ "件商品");
this.notifyAll();
}
}
public void removeData() {
synchronized (this) {
while (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fields[1].setText(Thread.currentThread().getName() + count--
+ "件商品");
this.notifyAll();
}
}
public static void main(String[] args) {
Store s = new Store(5);
}
}
public class Producer extends Thread{ private Store s; public Producer(Store s){ this.s=s; } public void run(){ while(true){ s.addData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Consumer extends Thread{ private Store s; public Consumer(Store s){ this.s=s; } public void run(){ while(true){ s.removeData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Producer extends Thread{ private Store s; public Producer(Store s){ this.s=s; } public void run(){ while(true){ s.addData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Consumer extends Thread{ private Store s; public Consumer(Store s){ this.s=s; } public void run(){ while(true){ s.removeData(); try { Thread.sleep((int)(Math.random()*300)); } catch (InterruptedException e) { e.printStackTrace(); } } } }