Chiwa Kantawong (Pea)
1 min readJul 22, 2021

ใช้ Semaphore ใน Java

ยังจำได้ไหมสมัยเราเป็นละอ่อนน้อยตอนเป็น freshy ในมหาวิทยาลัยเราได้ศึกษา Semaphore มาแล้วบ้าง วันนี้เราจะมี Implement Semaphore ใน Java กัน

แล้วได้ Semaphore มันคืออะไรล่ะ เอาง่ายๆ ก็คือการจำกัดจำนวน shared resource ที่มีอยู่จำกัดให้ applicationใช้งาน เอาไงดี แบบนี้นะ สมมติว่า เรามี การทำงานที่ต้องใช้ resource อะไรบางอย่างอย่างจำกัด เราจำกัดว่า มันสามารถเข้าใช้ได้แค่ n process เท่านั้นที่จะเข้าใช้งานพร้อมกันได้ process ที่ n+1 เป็นต้นไปก็ต้องรอจนกว่า process ที่ใช้งานก่อนหน้าจะ คืน process ให้ เป็นแบบนี้ไปเรื่อยๆ

ตัวอย่างนี้จะเป็นตัวอย่างง่ายๆ เราจะสร้าง Thread ขึ้นมา แต่บะ Thread จะใช้ resource บางอย่างที่เราจะจำกัดให้เข้าใช้งานได้พร้อมกันแค่ 5 Thread เท่านั้น

package com.zengcode.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class SemaphoreDemo {

public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(5);
ExecutorService service = Executors.newFixedThreadPool(100);

IntStream.range(1, 1000).forEach(i -> service.execute(new Task(semaphore, i)));

service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
}

static class Task implements Runnable {

Semaphore semaphore;
int threadNumber;

public Task(Semaphore semaphore, int threadNumber) {
this.semaphore = semaphore;
this.threadNumber = threadNumber;
}

@Override
public void run() {
System.out.println("Thread number "+ threadNumber+ " started.");
try {
System.out.println("Thread number "+ threadNumber+ " waiting for resource.");
semaphore.acquireUninterruptibly();
System.out.println("Thread number "+ threadNumber+ " using for resource.");
// do something with limited resource
Thread.sleep(1000);

} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
System.out.println("Thread number "+ threadNumber+ " released resource.");
}
}
}
}

ลองเอาไปปรับใช้กับงานที่ทำดูนะครับ ไม่ยากเลยใช่ไหมหล่ะ

Chiwa Kantawong (Pea)
Chiwa Kantawong (Pea)

Written by Chiwa Kantawong (Pea)

Software Development Expert at Central Tech

No responses yet