What Are Threads?

Let us start by looking at a simple program that uses two threads. This pro­gram moves money between bank accounts. We make use of a Bank class that stores the balances of a given number of accounts. The transfer method transfers an amount from one account to another. See Listing 12.2 for the implementation.

In the first thread, we will move money from account 0 to account 1. The second thread moves money from account 2 to account 3.

Here is a simple procedure for running a task in a separate thread:

  1. Place the code for the task into the run method of a class that implements the Runnable interface. That interface is very simple, with a single method:

public interface Runnable

{

void run();

}

Since Runnable is a functional interface, you can make an instance with a lambda expression:

Runnable r = () -> { task code };

  1. Construct a Thread object from the Runnable:

var t = new Thread(r);

  1. Start the thread:

t.start();

To make a separate thread for transferring money, we only need to place the code for the transfer inside the run method of a Runnable, and then start a thread:

Runnable r = () ->{

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)

{

}

};

var t = new Thread(r);

t.start();

For a given number of steps, this thread transfers a random amount, and then sleeps for a random delay.

We need to catch an InterruptedException that the sleep method threatens to throw. We will discuss this exception in Section 12.3.1, “Interrupting Threads,” on p. 743. Typically, interruption is used to request that a thread terminates. Accordingly, our run method exits when an InterruptedException occurs.

Our program starts a second thread as well that moves money from account 2 to account 3. When you run this program, you get a printout like this:

As you can see, the output of the two threads is interleaved, showing that they run concurrently. In fact, sometimes the output is a little messier when two output lines are interleaved.

That’s all there is to it! You now know how to run tasks concurrently. The remainder of this chapter tells you how to control the interaction between threads.

The complete code is shown in Listing 12.1.

Source: Horstmann Cay S. (2019), Core Java. Volume I – Fundamentals, Pearson; 11th edition.

Leave a Reply

Your email address will not be published. Required fields are marked *