2015-01-12 3 views
2

자바 멀티 쓰레드를 배우고 JAVA로 경쟁 조건을 만들려고했습니다. 그리고 이것은 내 코드입니다.JAVA에서 경쟁 조건을 다시 만드는 방법은 무엇입니까?

package com.company; 

public class Account { 
    private double balance = 100; 

    public double getBalance() { 
     return balance; 
    } 

    public void setBalance(double balance) { 
     this.balance = balance; 
    } 
    public boolean withdraw(double amount,String name){ 

     if(this.getBalance()>amount){ 
      this.setBalance(this.getBalance() - amount); 
      System.out.println(Thread.currentThread().getName() + " withdraw " + amount); 
      System.out.println("Hello, " + Thread.currentThread().getName() + " You current balance is " + this.getBalance()); 

      return true; 
     } 
     else{ 
      System.out.println("Sorry, " + Thread.currentThread().getName() + ". Your current balance is " + this.getBalance() + " and you cannot withdraw " + amount); 
      //System.out.println("Welcome, " + Thread.currentThread().getName() + " You current balance is " + this.getBalance()); 

      return false; 
     } 
    } 
} 

Supposingly
package com.company; 
public class Main implements Runnable { 
    Account account = new Account(); 
    public static void main(String[] args){ 
      Main main = new Main(); 
      for(int i= 0; i< 2; i++) { 
       Thread c1 = new Thread(main, "customer" + i); 
       c1.start(); 
      } 
    } 

    @Override 
    public void run() { 
     System.out.println(Thread.currentThread().getName() + "'s balance is " + account.getBalance()); 
     account.withdraw(60, Thread.currentThread().getName()); 
     // 
    } 
} 

, 이것은 경주 조건을 생성한다 메인 클래스는,이 명 고객은 같은 시간에 60 달러를 인출하고 getBalance()는 각 사용자 지정이 철회 할 수 있음을 나에게 보여 주어야한다 60 달러이고 잔액은 고객 당 40 달러입니다. 그러나 나는 이것을 결코 재현 할 수 없다. 나는 무엇을 잘못 했는가?

+0

중단 점이있는 "중요한 위치"에서 스레드를 중지하려고 할 수 있습니다. 또는 Thread # sleep을 삽입하여 줄 사이의 속도를 늦추십시오. – Thilo

+0

또한, '휘발성'또는 '동기화 됨'이 없으면 클래스가 여러 스레드간에 상태를 제대로 게시 할 수 있다고 보장 할 수 없습니다. – Thilo

+0

출력물이 보이십니까? 너 뭐가 보이니? – Robbert

답변

1

경쟁 조건을 재생하는 것이 반드시 쉬운 것은 아닙니다. 종종 스레드 스케줄러의 타이밍에 의존합니다.

당신은 당신의 스레드 중 하나를함으로써 조금이 영향을 미칠 수도이 보장되지는 않습니다

if (this.getBalance() > amount) { 
    if (Thread.currentThread().getName().equals("customer0")) 
     try { 
      Thread.sleep(1); // simulates a quicker thread context switch 
     } catch (InterruptedException e) {} 
    this.setBalance(this.getBalance() - amount); 
    System.out.println(Thread.currentThread().getName() + " withdraw " + amount); 
    System.out.println("Hello, " + Thread.currentThread().getName() + " You current balance is " + this.getBalance()); 

    return true; 
} 

주 잔다. 그것은 내 시스템에서 작동했지만, 당신 시스템에서는 작동하지 않을 수도 있습니다. 그렇기 때문에 경쟁 조건이 짜증나는 이유입니다. 그들은 일관되게 재생산하기가 어렵습니다.

+0

고맙습니다. 수면 시간을 늘리면 효과가 있습니다. – user454232

관련 문제