0
0

More than 1 year has passed since last update.

複数methodをまとめて排他

Posted at

first,second,thirdをまとめて排他にするときは
別class化(Test)してReentranLockを持たせる。
lockするとunlockするまでlockできない。
Reentrantを共有ため、threadは単一のTestを共有

class Test {
    final ReentrantLock re = new ReentrantLock();
    void lock() {
        this.re.lock();
    }
    void unlock() {
        this.re.unlock();
    }
    void first() {
        System.out.println(Thread.currentThread().getId() + ":1");
    }
    void second() {
        System.out.println(Thread.currentThread().getId() + ":2");
    }
    void third() {
        System.out.println(Thread.currentThread().getId() + ":3");
    }    
    void fourth() {
        System.out.println(Thread.currentThread().getId() + ":4");
    }
}
class Task implements Runnable {
    Test t;
    Task (Test t) {
        this.t = t;
    }
    @Override
    public void run() {
        t.lock();
        t.first();
        t.second();
        t.third();
        t.unlock();
    }
}
class Task2 implements Runnable {
    Test t;
    Task2 (Test t) {
        this.t = t;
    }
    @Override
    public void run() {
        t.lock();
        t.fourth();
        t.unlock();
    }
}

public class Outer {
    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(3);
        Test t = new Test();
        es.submit(new Task(t));
        es.submit(new Task(t));
        es.submit(new Task2(t));
        es.shutdown();
    }
}
14:1
14:2
14:3
13:1
13:2
13:3
15:4
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0