Em đang học về synchronized trong Java và có một đoạn code như sau:
public void run() { //hàm run của thread
//chạy 1 vòng for loop 10 lần
// trong vòng for gọi đến method test()
}
public synchronized void test() {
//code
}
Sau đó em tạo 2 thread với hàm run() như trên và em cho cả 2 start. Theo em nghĩ chỉ có method test() là synchronized nên sau khi chạy xong test thì thread 1 sẽ dừng lại chuyển đổi cho thread 2. Thế nhưng kết quả của code của em thì thread 1 lại chạy tận 10 vòng loop mới dừng lại và chuyển cho thread 2. Anh chị nào giải thích lý do giùm em với ạ?
Code cụ thể:
import java.io.*;
import java.util.*;
public class Test implements Runnable{
private BankAccount account = new BankAccount();
public static void main(String[] args) {
Test t = new Test();
Thread one = new Thread(t);
Thread two = new Thread(t);
one.setName("Ryan");
two.setName("Monica");
one.start();
two.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
makeWithdraw(10);
if (account.getBalance() < 0) {
System.out.println("Overdrawn!");
}
}
}
public synchronized void makeWithdraw(int amount) {
if (account.getBalance() >= amount) {
System.out.println(Thread.currentThread().getName() + " is about to withdraw");
try {
System.out.println(Thread.currentThread().getName() + " is going to sleep");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " woke up");
account.withdraw(amount);
System.out.println(Thread.currentThread().getName() + " complete the withdraw");
} else {
System.out.println("Not enough money for " + Thread.currentThread().getName());
}
}
}
class BankAccount {
private int balance = 100;
public int getBalance() {
return this.balance;
}
public void withdraw(int amount) {
balance = balance - amount;
}
}