JavaのLock

Lockする。

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();
                }
            });
        }
        es.shutdown();
    }
    
    public static void add() {
        boolean locked = false;
        try {
            locked = lock.tryLock(3L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {}
        if (locked) {
            count++;
            System.out.println(Thread.currentThread().getName() + " up: " + count);
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " unlock");
            }
        } else {
            System.out.println(Thread.currentThread().getName() + " missed lock");
        }
    }
}

実行結果。

$ java -version
java version "1.7.0_79"
OpenJDK Runtime Environment (rhel-2.5.5.1.el7_1-x86_64 u79-b14)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)
$ java LockSample
pool-1-thread-1 up: 1
pool-1-thread-3 missed lock
pool-1-thread-2 missed lock
pool-1-thread-1 unlock
pool-1-thread-3 up: 2
pool-1-thread-2 missed lock
pool-1-thread-1 missed lock
pool-1-thread-2 missed lock
pool-1-thread-3 unlock
pool-1-thread-1 up: 3
pool-1-thread-2 missed lock
pool-1-thread-3 missed lock
pool-1-thread-1 unlock

できた。

Comments

Leave a Reply

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