Created
          January 17, 2017 04:27 
        
      - 
      
- 
        Save ee7klt/f2c87f65cab186a8c00e9d013692c532 to your computer and use it in GitHub Desktop. 
    parallelism on the jvm ii
  
        
  
    
      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
    
  
  
    
  | class Account(private var amount: Int = 0) { | |
| def transfer(target:Account, n: Int) = | |
| this.synchronized { | |
| target.synchronized { | |
| this.amount -= n | |
| target.amount += n | |
| } | |
| } | |
| } | |
| def startThread(a: Account, b: Account, n: Int) = { | |
| val t = new Thread { | |
| override def run() { | |
| for (i <- 0 until n) { | |
| a.transfer(b,1) | |
| } | |
| } | |
| } | |
| t.start() | |
| t | |
| } | |
| val a1 = new Account(500000) | |
| val a2 = new Account(700000) | |
| val t = startThread(a1, a2, 150000) | |
| vat s = startThread(a2, a1, 150000) | |
| t.join() | |
| s.join() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment