场景:一支枪可盛20发子弹,运用多线程,实现子弹不停上膛、射出的过程。
public class Bullet {
private int type;
private String name;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BulletDealer {
private int size;
private List<Bullet> queue = new ArrayList<>();
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
public BulletDealer(int size){
this.size = size;
}
public void produce(Bullet e) {
try {
lock.lock();
// System.out.println("procduce");
while (queue.size() == size) {
System.out.println("弹膛满了");
try {
notFull.await();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
queue.add(e);
System.out.println("上膛");
notEmpty.signal();
} finally {
// System.out.println("producer unlock");
lock.unlock();
}
}
public void consume(){
try {
lock.lock();
while (queue.size() == 0) {
System.out.println("没子弹了");
try {
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.remove(0);
System.out.println("射击");
notFull.signal();
}finally {
//System.out.println("consumer unlock");
lock.unlock();
}
}
public static void main(String[] args){
BulletDealer dealer = new BulletDealer(20);
for(int i=0; i<10; i++){
new Thread(new Consumer(dealer)).start();
}
for(int j=0; j<10; j++){
Bullet e = new Bullet();
e.setName("子弹:" + j);
e.setType(1);
dealer.produce(e);
new Thread(new Producer(dealer, e)).start();
}
}
}
public class Producer implements Runnable{
private BulletDealer dealer;
private Bullet bullet;
public Producer(BulletDealer dealer, Bullet bullet){
this.dealer = dealer;
}
@Override
public void run() {
dealer.produce(bullet);
}
}
public class Consumer implements Runnable {
private BulletDealer dealer;
public Consumer(BulletDealer dealer){
this.dealer = dealer;
}
@Override
public void run() {
dealer.consume();
}
}