1st thread b1.deposit() lock b1
2nd thread b2.deposit() lock b2
この状態で処理を進めると
1st thread b2.deposit() cannot update b2 because 2nd locked b2
2nd thread b1.deposit() cannot update b1 because 1st locked b1
class Bank {
int amount;
void deposit() {
amount++;
}
void withdrawal() {
amount--;
}
}
public class Outer {
public static void main(String[] args) {
ExecutorService e = Executors.newFixedThreadPool(10);
Bank b1 = new Bank();
Bank b2 = new Bank();
e.submit(() -> {
try {
Thread.sleep(100);
synchronized(b1) {
b1.deposit();
synchronized(b2) {
b2.deposit();
}
}
} catch (InterruptedException ex) {
Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
}
});
e.submit(() -> {
try {
Thread.sleep(100);
synchronized(b2) {
b2.deposit();
synchronized(b1) {
b1.deposit();
}
}
} catch (InterruptedException ex) {
Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
}
});
e.shutdown();
int i;
int j=0;
while(true){
i = Thread.activeCount();
System.out.println("active count:" + i);
j++;
try {
Thread.sleep(j * 1000);
} catch (InterruptedException ex) {
Logger.getLogger(Outer.class.getName()).log(Level.SEVERE, null, ex);
}
if (i==0|j>5) break;
}
}
}
current thread
1st thread
2st thread
count:3
active count:3
active count:3
active count:3
active count:3
active count:3
active count:3