Reputation: 434
I'm reading the book Core java by Cay S. Horstmann. I'm confused with this code in the section concurrency.
We construct a new thread and pass our Runnable
task to it, I understand up until this. The part that confuses me is that, we call the start()
method to these new threads on after another. My question is that when does the first call to the start()
method returns to main()
method. Is it after the new thread has finished its task or does it returns while that new thread is running the task?
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;
}
}
Upvotes: 0
Views: 1533
Reputation:
Yes it returns when the moment it handles the new run
method to the new thread.
Then the thread pooling handles the control flow of the threads. Refer to threads and concurrency in java
Upvotes: 0
Reputation: 869
The start method returns immediately & the Main Thread continues running.
You can see this happening with this little Proggy:
import java.time.Duration;
import java.time.ZonedDateTime;
public class Runner {
public static void main(final String[] args) throws Exception {
final Runnable runner = () -> {
System.out.println(ZonedDateTime.now() + " " + Thread.currentThread().getName() + " Running...");
sleep(Duration.ofSeconds(9));
System.out.println(ZonedDateTime.now() + " " + Thread.currentThread().getName() + " Done.");
};
System .out.println(ZonedDateTime.now() + " " + Thread.currentThread().getName() + " starting Thread 1...");
new Thread(runner).start();
System .out.println(ZonedDateTime.now() + " " + Thread.currentThread().getName() + " starting Thread 2...");
new Thread(runner).start();
sleep(Duration.ofSeconds(3));
System .out.println(ZonedDateTime.now() + " " + Thread.currentThread().getName() + " done.");
}
private static void sleep(final Duration duration) {
try {
Thread.sleep(duration.toMillis());
}
catch (final InterruptedException e) {}
}
}
Upvotes: 1
Reputation: 841
Start method finish immediately after creating new thread. The result of start method is two threads that are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
The start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in a separate thread.
Execution of starting thread in main thread is like any other statement. If you want to wait for the thread to finish you must use join method on it:
Thread t1 = new Thread(task1).start();
t1.join();
Thread ends its execution when its run method finish.
Upvotes: 0