package com.training;

public class ConcurrencyProcess {

public static void main(String[] args) throws InterruptedException {

Account a1 = new Account(10000,”origin”);

Account a2 = new Account(10000,”destination”);

Thread t1 = new Thread( new TransferManager(a1,a2));

Thread t2 = new Thread( new TransferManager(a2,a1));

t1.start();

t2.start();

t1.join();

}

}

package com.training;

public final class Account {

private int balance = 0;

private String name;

public Account(int balance, String name) {

super();

this.balance = balance;

this.name = name;

}

public synchronized void add(Integer amount) {

this.balance = balance + amount;

}

public synchronized void sub(Integer amount) {

this.balance = balance – amount;

}

public synchronized int getBalance() {

return balance;

}

public synchronized void setBalance(int balance) {

this.balance = balance;

}

}

package com.training;

public class TransferManager implements Runnable {

private Account origin;

private Account destination;

public TransferManager(Account a1, Account a2) {

origin = a1;

destination = a2;

}

@Override

public void run() {

while (true) {

// synchronized (origin) {

// synchronized (destination) {

// origin.sub(1);

// destination.add(100);

// System.out.println(origin.getBalance() + ” ” + destination.getBalance());

// }

// }

origin.sub(1);

destination.add(1);

System.out.println(origin.getBalance() + ” ” + destination.getBalance());

}

}

}

Yukarda paylaştığım classlar ile bir deadlock oluşturmaya çalışıyorum. Account class’ına synchronized anahtar kelimesini eklediğimde oluşmuyor ancak TransferManager class’ı üzerinde comment li alanları açıp (Diğerlerini kapatın) çalıştırdığımda deadlock oluşuyor. Tamamen deneme amaçlı olduğu için neden böyle bir şey yapıyorsun demeyin 🙂