生产者和消费者
生产者 : 不停的生产商品
消费者 : 不停的消费商品
多线程
public class mainProgram {
public static void main(String[] args) {
// 生产者
Producer p = new Producer();
Thread t = new Thread(p);
t.start();
// 消费者
Customer c = new Customer();
Thread t2 = new Thread(c);
t2.start();
}
}
生产者
public class Producer implements Runnable {
static int thing = 0;
static final Object Object = new Object();
@Override
public void run() {
while (thing < 200) {
synchronized (Object) {
thing += 2;
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--> 剩余: " + thing + "个");
}
}
}
}
消费者
public class Customer implements Runnable{
@Override
public void run() {//Producer.thing != 0
while (true) {
synchronized (Producer.Object) {
if(Producer.thing > 0){
Producer.thing --;
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--> 剩余: " + Producer.thing + "个");
}
}
}
}
}