Я читаю книгу Core java Кей С. Хорстманн. Я запутался с этим кодом в разделе параллелизма. Мы создаем новую нить и передаем ей задачу Runnable
, я понимаю, до этого. Меня смущает то, что мы вызываем метод start()
для этих новых потоков за другим. Мой вопрос заключается в том, что когда первый вызов метода start()
возвращается к методу main()
. Это после того, как новый поток завершил свою задачу, или он возвращается, когда этот новый поток выполняет задачу?
import java.util.Arrays;
public class Main{
public static final int DELAY = 10;
public static final int STEPS = 100;
public static final double MAX_AMOUNT = 1000;
public static void main(String[] args) {
var bank = new Bank(4, 100000);
Runnable task1 = () -> {
try {
for (int i = 0; i < STEPS; i++){
double amount = MAX_AMOUNT * Math.random();
bank.transfer(0, 1, amount);
Thread.sleep((int) (DELAY * Math.random()));
}
}catch (InterruptedException e) {
}
};
Runnable task2 = () ->{
try{
for (int i = 0; i < STEPS; i++){
double amount = MAX_AMOUNT * Math.random();
bank.transfer(2, 3, amount);
Thread.sleep((int) (DELAY * Math.random()));
}
}
catch (InterruptedException e){
}
};
new Thread(task1).start();
new Thread(task2).start();
}
}
class Bank{
private final double[] accounts;
/**
* Constructs the bank.
* @param n the number of accounts
* @param initialBalance the initial balance for each account
*
**/
public Bank(int n, double initialBalance){
accounts = new double[n];
Arrays.fill(accounts, initialBalance);
}
/**
* Transfers money from one account to another.
* @param from the account to transfer from
* @param to the account to transfer to 27
* @param amount the amount to transfer 28
**/
public void transfer(int from, int to, double amount){
if (accounts[from] < amount) return;
System.out.print(Thread.currentThread());
accounts[from] -= amount;
System.out.printf(" %10.2f from %d to %d", amount, from, to);
accounts[to] += amount;
System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());
}
/**
* Gets the sum of all account balances.
* @return the total balance 42
**/
public double getTotalBalance(){
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
}
/**
* Gets the number of accounts in the bank.
* * @return the number of accounts 56
**/
public int size(){
return accounts.length;
}
}