公司扫码枪技术---使用Semaphore进行数据验证(创建字符串)

我们公司项目开发中:运用场景扫码枪扫码时,我们多个会场同时进行扫码,进入库中
验证不同二维码的正确性,这个实验的功能是同时有若干个线程可以访问池中的数据,
但同时只有一个线程可以取得数据进行验证,只有验证数据正确性,以后再返回给前端数据,

package com.zcw.demo1;

/**
 * @ClassName : MyThread
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 16:06
 */
public class MyThread extends Thread {
    private TestListPool testListPool;
    public MyThread(TestListPool testListPool){
        super();
        this.testListPool = testListPool;
    }
    @Override
    public void run(){
        for(int i =0; i<Integer.MAX_VALUE;i++){
            String getString = testListPool.get();
            System.out.print(Thread.currentThread().getName()+"取得值" +getString+"\n");
            testListPool.put(getString);
        }
    }

    public static void main(String[] args) {
        TestListPool testListPool = new TestListPool();
        MyThread[] threads = new MyThread[12];

        for(int i =0;i<threads.length;i++){
            threads[i] = new MyThread(testListPool);
        }
        for(int i =0;i<threads.length;i++){
            threads[i].start();
        }
    }
}
package com.zcw.demo1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : TestListPool
 * @Description : 使用Semaphore创建字符串池,若干个线程可以访问池中的数据,但同时只有一个线程可以取得数据
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 15:26
 */
public class TestListPool {

    private int poolMaxSize=3;
    private int semaphorePermits =5;
    private List<String> list = new ArrayList<String>();
    private Semaphore concurrencySemaphore = new Semaphore(semaphorePermits);
    private ReentrantLock lock  = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public TestListPool(){
        super();
        for (int i=0;i<poolMaxSize;i++){
            list.add("测试数据"+(i+1));
        }
    }
    public String get(){
        String getString = null;
        try{
            concurrencySemaphore.acquire();
            lock.lock();
            while(list.size() ==0){
                condition.await();
            }
            getString = list.remove(0);
            lock.unlock();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getString;
    }
    public void put(String  stringValue){
        lock.lock();
        list.add(stringValue);
        condition.signalAll();
        lock.lock();
        concurrencySemaphore.release();
    }
}

发布了475 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_32370913/article/details/105576923