Created
April 26, 2018 04:23
-
-
Save lunaspeed/9186b9d4b6bebf9a971de922cba2643d to your computer and use it in GitHub Desktop.
transfer problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
public final class Transfer { | |
private Transfer(){} | |
public static void transfer(User from, User to, BigDecimal amount) { | |
synchronized (from) { | |
if(from.getBalance().compareTo(amount) >= 0) { | |
synchronized (to) { | |
from.setBalance(from.getBalance().subtract(amount)); | |
to.setBalance(to.getBalance().add(amount)); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
User user1 = new User("abc", new BigDecimal("1000000")); | |
User user2 = new User("xyz", new BigDecimal("1000000")); | |
Object waiter = new Object(); | |
Thread t1 = new Trans(user1, user2, waiter); | |
Thread t2 = new Trans(user2, user1, waiter); | |
//Thread t3 = new Trans(user2, user1, waiter); | |
t1.start(); | |
t2.start(); | |
//t3.start(); | |
waiter.notifyAll(); | |
t1.join(); | |
t2.join(); | |
//t3.join(); | |
System.out.println("transfer finished, user1 has "+ user1.getBalance().toPlainString() + ", user2 has " + user2.getBalance().toPlainString()); | |
} | |
static class Trans extends Thread { | |
private static final BigDecimal tAmount = new BigDecimal("5"); | |
final User f; | |
final User t; | |
final Object w; | |
public Trans(User from, User to, Object waiter) { | |
f = from; | |
t = to; | |
w = waiter; | |
} | |
@Override | |
public void run() { | |
try { | |
w.wait(); | |
} | |
catch (Exception e) { | |
} | |
for(int i = 0; i < 10000; i++) { | |
System.out.println("transfer from " + f.getId() + " to " + t.getId()); | |
transfer(f, t, tAmount); | |
} | |
} | |
} | |
public static class User { | |
private String id; | |
private BigDecimal balance; | |
public User(String id, BigDecimal balance) { | |
this.id = id; | |
this.balance = balance; | |
} | |
public String getId() { | |
return id; | |
} | |
public void setId(String id) { | |
this.id = id; | |
} | |
public BigDecimal getBalance() { | |
return balance; | |
} | |
public void setBalance(BigDecimal balance) { | |
this.balance = balance; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment