あるフリーランスエンジニアの色んなメモ!! ITスキル・ライフハックとか

Java:セマフォ(Semaphore)の使い方

セマフォ(Semaphore)を使用することにより、一度に実行されるスレッドの数を制限する


実装例

mypackage.MyRunnable.java

スレッドで実行する処理

package mypackage;

import java.util.concurrent.Semaphore;

public class MyRunnable implements Runnable {

    private Semaphore semaphore;
    private String[] args;

    public MyRunnable(Semaphore s, String[] args) {
        this.semaphore = s;
        this.args = args;
    }

    private void execute(String[] args) {
        // threadで実行する処理
        ...
    }

    @Override
    public void run() {
        // runメソッド内でセマフォの取得・解放を行う
        try {
            this.semaphore.acquire();
            execute(this.args);
        } catch (InterruptedException e) {
            ...
        } finally {
            this.semaphore.release();
        }
    }
}

mypackage.Main.java

スレッドを制御する処理

package mypackage;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;

public class Main {

    public static void main(String[] args) {
        // threadを4つまで起動する
        Semaphore s = new Semaphore(4, true);
        ArrayList<Thread> thread_list = new ArrayList<Thread>();

        // threadを起動
        for (...) {
            Thread t = new Thread(new MyRunnable(s, new String[] {...}));
            t.start();
            thread_list.add(t);
        }

        // threadの終了を待つ
        for (Thread t: thread_list) {
            try {
                t.join();
            } catch (InterruptedException e) {
                ...
            }
        }
    }
}
comments powered by Disqus