生产者:
public class GoodsAdd implements Runnable{
private TestEntity i;
public GoodsAdd(TestEntity i) {
this.i = i;
}
public void add() {
synchronized (i) {
if(i.getInteger()==null) {
i.setInteger(0);
}
i.setInteger(i.getInteger()+1);
System.out.println(Thread.currentThread().getName()+i.getInteger());
i.notify();
}
}
@Override
public void run() {
add();
}
}
消费者:
public class GoodsDelete implements Runnable{
private TestEntity i;
public GoodsDelete(TestEntity i) {
this.i = i;
}
public void delete() {
synchronized (i) {
if(i.getInteger()==null){ //确保消费者和生产者人数一样,把线程阻塞
try {
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while( i.getInteger()<=0) {
try {
i.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i.setInteger(i.getInteger()-1);
System.out.println(Thread.currentThread().getName()+i.getInteger());
}
}
@Override
public void run() {
delete();
}
}
生产的数量:
public class Test {
public static void main(String[] args) {
TestEntity count = new TestEntity();
GoodsAdd pin = new GoodsAdd(count);
GoodsDelete pinDelete = new GoodsDelete(count);
for (int i = 0; i < 100; i++) {
Thread add = new Thread(pin,"add: ");
Thread delete = new Thread(pinDelete,"delete: ");
delete.start();
add.start();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count.getInteger());
}
}
测试类:
public class Test {
public static void main(String[] args) {
TestEntity count = new TestEntity();
GoodsAdd pin = new GoodsAdd(count);
GoodsDelete pinDelete = new GoodsDelete(count);
for (int i = 0; i < 100; i++) {
Thread add = new Thread(pin,"add: ");
Thread delete = new Thread(pinDelete,"delete: ");
delete.start();
add.start();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count.getInteger());
}
}
为什么生产的商品数要声明到一个类里面呢?
如果直接用integer++的话,notify()方法会报错,这是因为synchronized关键字锁的对象和notify()调用的对象不是同一个。
有错的地方还望各位大侠指教。