public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(1);
        LockEntity lockEntity = new LockEntity();
        new Thread(new PThread(list, lockEntity)).start();
        new Thread(new CThread(list, lockEntity)).start();
    }
}

/**
 * 生产者
 */
class PThread implements Runnable {
    private List<String> list;
    private LockEntity lockEntity;
    private AtomicInteger integer = new AtomicInteger();

    public PThread(List<String> list, LockEntity lockEntity) {
        this.list = list;
        this.lockEntity = lockEntity;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                //上锁
                lockEntity.lock.lock();
                if (lockEntity.flag) {
                    String data = integer.getAndIncrement() + "";
                    list.add(data);
                    System.out.println("生产者线程,生产一个数据:" + data);
                    lockEntity.flag = false;
                    lockEntity.condition.signal();  //唤醒
                } else {
                    lockEntity.condition.await(); //等待
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lockEntity.lock.unlock();
            }
        }
    }
}


class CThread implements Runnable {
    private List<String> list;
    private LockEntity lockEntity;

    public CThread(List<String> list, LockEntity lockEntity) {
        this.list = list;
        this.lockEntity = lockEntity;

    }

    @Override
    public void run() {
        while (true) {
            try {
                lockEntity.lock.lock();
                if (!lockEntity.flag) {
                    String data = list.remove(0);
                    System.out.println("消费者线程,消费了一个数据:" + data);
                    lockEntity.flag = true;
                    lockEntity.condition.signal();
                } else {
                    lockEntity.condition.await();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lockEntity.lock.unlock();
            }
        }
    }
}

/**
 * 封装锁等信息
 */
class LockEntity {
    public boolean flag = true;
    public Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
}


测试结果如下

 


posted on 2018-09-30 14:49  显示账号  阅读(201)  评论(0编辑  收藏  举报