JavaのExecutorService

べんり。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockSample {
    private static final Lock lock = new ReentrantLock();
    private static int count = 0;
    
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            es.execute(new Runnable() {
                @Override
                public void run() {
                    add();
                }
            });
            print("created " + i);
        }
        es.shutdown();
        try {
            for (int i = 0; !es.awaitTermination(1L, TimeUnit.SECONDS) && i < 20; i++) {
                print(i + " waiting...");
            }
        } catch (InterruptedException e) {
            print(e.toString());
        }
        print("terminated");
    }
    
    public static void add() {
        boolean locked = false;
        try {
            locked = lock.tryLock(3L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {}
        if (locked) {
            count++;
            print("up: " + count);
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
            } finally {
                lock.unlock();
                print("unlock");
            }
        } else {
            print("missed lock");
        }
    }
    
    public static void print(String msg) {
        System.out.println("[" + Thread.currentThread().getName() + "] " + msg);
    }
}

実行結果。

$ java LockSample
[main] created 0
[pool-1-thread-1] up: 1
[main] created 1
[main] created 2
[main] created 3
[main] created 4
[main] created 5
[main] created 6
[main] created 7
[main] created 8
[main] created 9
[main] 0 waiting...
[main] 1 waiting...
[pool-1-thread-2] missed lock
[pool-1-thread-3] missed lock
[main] 2 waiting...
[main] 3 waiting...
[pool-1-thread-1] unlock
[pool-1-thread-1] up: 2
[main] 4 waiting...
[pool-1-thread-2] missed lock
[pool-1-thread-3] missed lock
[main] 5 waiting...
[main] 6 waiting...
[main] 7 waiting...
[pool-1-thread-2] missed lock
[pool-1-thread-3] missed lock
[main] 8 waiting...
[pool-1-thread-1] unlock
[pool-1-thread-2] up: 3
[main] 9 waiting...
[main] 10 waiting...
[pool-1-thread-3] missed lock
[main] 11 waiting...
[main] 12 waiting...
[main] 13 waiting...
[pool-1-thread-2] unlock
[main] terminated

分かりやすい。

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *