Witscale Test Center

12.1 Thread basics


12.1 Thread basics

For all the programs we have studied so far, there was only one thread or sequence of execution. In other words, when you execute a Java program, the statements in it are executed one after another until the program finishes it job.  For instance, if you write a program that pays your utility bill, it will do so in a sequential fashion. It may follow steps some thing like:

1.       Access your bank account

2.       Validate whether sufficient balance to pay the bill

3.       Debit the bill amount from your account

4.       Credit the utility company’s account

5.       Displays you the receipt and exits

In a single-threaded execution, a thread will execute these steps one after another. However, the steps 3 and 4 may take a while as often the banks perform the actual financial transaction overnight. So with a single threaded solution, you will never be able to confirm the payment until the transaction is actually complete.  The better way is to confirm payment right after second step. The actual transactions can be performed in the background. Thus after the step three, we can introduce one more thread of execution to perform transactions. Table 12.1 shows the difference between single threaded and multithreaded application.

 

Table 12.1 Comparing single threaded solution and multithreaded approaches for application for payment the utility bill

 

Single-threaded solution

Multi-threaded solution



 

Obviously, the multithreaded solution has been well responsive to the user. It gives the user an illusion of performance even if both applications taking the same time to pay the bill. The threads are shown with a stick-man metaphor. We will use this metaphor throughout the chapter. Imagine a thread as a worker who does the job it is asked to do. In single-threaded solution, only one thread is working so all the steps are done sequentially. However, in multi-threaded application, the thread asks another thread to do the job that can be done independently in parallel. Thus, your application will be responsive to the user immediately after the validation. Moreover, the job is still done correctly. This is especially beneficial in complex applications where multiple threads can do much better job (and make applications more responsive) than a single thread. Now that we know some of the advantages of having multithreaded solutions, let us see what exactly a thread is and how to define one.