0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

dead lock of thread

Posted at

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
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?