하나의 은행 계좌에서 돈을 인출하고 입금하는 두 명의 사용자를 시뮬레이트하기 위해 멀티 스레딩을 사용하려고합니다. 두 명의 사용자가 단일 공유 변수에 대해 조치를 취하고 물론 계정 잔액을 나타내는 것이 좋습니다.여러 스레드에서 전역 필드 액세스 및 편집
돈을 입금하거나 인출하기위한 조치는 무작위로 1 개 또는 2 개 선택됩니다 (입금 및 인출). 예금 할 때 예금 조치를 1 초, 철회 조치를 0.5 초로하고 싶습니다. 이 시간 간격에서 스레드는 다른 스레드가 자체를 철회/입금하기 전에 조치를 완료 할 때까지 기다려야합니다.
그러나 가장 큰 문제는 두 스레드가 각각 단일 공유 숫자 필드 인 저울을 편집 할 수 있다는 것입니다. 처음 시도했을 때, 각 쓰레드는 자체적 인 균형 인스턴스를 생성하고 별도로 작동했습니다. 인스턴스 필드가 아닌 전역 필드 "balance"에 영향을주는 각 스레드의 작업 (인출/입금)을 원합니다.
스레드 클래스 및 드라이버 클래스 지금까지 작성한 클래스는 다음과 같습니다.
스레드 작성자 클래스 :
public class BankAccountSim extends Thread{
public double balance = 1000;
public String threadName;
BankAccountSim(String name){
threadName = name;
}
public void run(){
System.out.println(threadName + "account initiated.");
while(true){
try{
Random rand = new Random();
int num = rand.nextInt(2) + 1;
if(num == 1){
System.out.println(threadName + " is depositing in the bank.");
balance += 1;
System.out.println("The new balance is " + balance + " dollars");
Thread.sleep(1000);
Thread.yield();
}
else{
System.out.println(threadName + " is withdrawing from the bank.");
balance -= 1;
System.out.println("The new balance is " + balance + " dollars.");
Thread.sleep(500);
Thread.yield();
}
}
catch(InterruptedException e){
System.out.println("Process terminated.");
}
}
}
}
나사 드라이버 클래스 :
import java.util.concurrent.ThreadLocalRandom;
import java.util.Random;
public class BankAccountSimDriver {
public static void main(String[] args){
Thread user1 = new BankAccountSim("user1");
Thread user2 = new BankAccountSim("user2");
user1.start();
user2.start();
}
}
당신은'balance' 정적을 만들 수 있고, 아마도 AtomicInteger –
을 사용할 수도 있습니다.'Thread'에서'BankAccountSim'을 확장하는 것보다는 간단하게 만드십시오. 이 클래스의 단일 인스턴스를 만든 다음 스레드에 전달하여 스레드에서 작업을 수행해야합니다. 'BankAccountSim'은 계좌에'withdraw' 또는'deposit'하는'synchronized' 메소드를 제공해야합니다. – MadProgrammer
그리고 정말로이 코드를 사용하고 싶다면 Money는 절대로'double '이되어서는 안됩니다. –