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