[동시 프로그래밍] - 세마포어 - 문자열 풀 생성

함께 쓰는 습관을 들이세요! "너겟 데일리 뉴 플랜 · 4월 업데이트 챌린지" 참여 9일차입니다. 클릭하시면 이벤트 내용을 보실 수 있습니다 .

세마포어를 사용하여 문자열 풀 만들기

Semaphore 클래스는 동시에 작업을 수행하는 스레드 수를 효과적으로 제한할 수 있으며, 이 기능은 풀 풀 기술에 적용할 수 있으며 풀 풀의 데이터에 동시에 액세스하는 스레드 수를 설정할 수 있습니다.

동시에 여러 스레드가 풀의 데이터에 액세스할 수 있지만 동시에 하나의 스레드만 데이터를 얻은 다음 사용 후 풀에 다시 넣을 수 있습니다.

문자열 풀 구현 코드:

public class ListPool {

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

    public ListPool(){
        super();
        for (int i = 0; i < poolMaxSize ; i++) {
            list.add("ozx"+(i+1));
        }
    }

    public String get(){
        String getValue = null;
        try {
            semaphore.acquire();
            reentrantLock.lock();
            while(list.size() == 0){
                condition.await();
            }
            getValue = list.remove(0);
            reentrantLock.unlock();
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getValue;
    }

    public void put(String value){
        reentrantLock.lock();
        list.add(value);
        condition.signalAll();
        reentrantLock.unlock();
    }
}

复制代码

스레드 클래스 코드:

@Slf4j
public class ListPoolThread implements Runnable {

    private ListPool listPool;

    public ListPoolThread(ListPool listPool){
        super();
        this.listPool=listPool;
    }


    @Override
    public void run() {
        for (int i = 0; i < Integer.MAX_VALUE ; i++) {
            String getValue = listPool.get();
            log.info("线程名:{} 获取的字符串的值:{}",Thread.currentThread().getName(),getValue);
            listPool.put(getValue);
        }
    }
}
复制代码

실행 중인 클래스 코드는 다음과 같습니다.

public class ListPoolTest {
    public static void main(String[] args) {
        ListPool listPool = new ListPool();
        ListPoolThread[] poolThreads = new ListPoolThread[10];
        for (int i = 0; i < poolThreads.length ; i++) {
            poolThreads[i] = new ListPoolThread(listPool);
        }
        for (int i = 0; i < poolThreads.length ; i++) {
            new Thread(poolThreads[i]).start();
        }
    }
}
复制代码

결과는 다음과 같습니다.

17:26:28.111 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.111 [Thread-2] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-2 获取的字符串的值:ozx2
17:26:28.111 [Thread-8] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-8 获取的字符串的值:ozx5
17:26:28.111 [Thread-7] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-7 获取的字符串的值:ozx4
17:26:28.111 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.113 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
17:26:28.113 [Thread-5] INFO com.ozx.concurrentprogram.semaphore.entity.ListPoolThread - 线程名:Thread-5 获取的字符串的值:ozx1
复制代码

추천

출처juejin.im/post/7085258436048486414