An Introduction to Java Thread Programming

An Introduction to Java Thread Programming

he concept of threaded programming isn’t new; most modern operating systems provide support for threads in some fashion. However, as widespread as threads are, the number of developers who have worked with them is fairly small. The cause of the problem is not clear?perhaps because threaded code is virtually unportable; perhaps because threaded programming requires techniques that aren’t familiar to many developers.

However, threaded programming is almost essential. Any substantial program is multithreaded. Java, by its very nature, solves portability problems, and the thread support in Java is so elegantly simple that any developer can pick up the mechanisms of thread programming with ease.

Threads, Defined
What precisely is a thread, however? A “thread” is shorthand for a “thread of control.” At its simplest, this is just a section of code executed independently of other threads of control within a single program. We’re all familiar with multitasking wherein an operating system can run more than one program at a time. A thread is much the same, but, conceptually, exists at a process level. That is, one process may be divided into multiple threads, executing simultaneously, all performing discrete tasks that contribute to the overall program.

The popularity of threads increased when graphical user interfaces became standard for desktop computers, as they gave the illusion of better performance. The programs didn’t really run any faster, but separate threads could be used to (for example) print a file and receive new keystrokes from the user. No longer would users need to wait for a document to print before they could continue working, as these programs invoke a separate thread to perform the printing task in the background.

Another advantage of a thread is its improved handling of blocking I/O. In Java, just like most programming languages, input is read from a stream. If an attempt is made to read data when none is currently available, the program will simply wait (block) until input becomes available and the read request is fulfilled. In most cases, this behavior is undesirable. While blocked, the appearance to the user will be that the program has hung, as any actions appear to be ignored. By using multithreading, the Java program can create a separate thread to read data from the desired input stream. And if this thread blocks, all other threads remain unaffected and can still perform servicing and processing in the meantime.

There is a potential problem with thread programming that requires special handling. See the sidebar “Busy Waiting.”

Creating a Java Thread
So, how does one actually create a multithreaded program? The following code composes a simple program that will demonstrate the fundamentals.

This simple, non-threaded, class exposes a method that merely loops from 0 to 100, printing “Hello world” on each iteration.

public class PrintHello{  public void run ()  {    for (int i = 0; i < 100; i++)      System.out.println ("Hello world");  }}
Now I’ll use a driver program to create and invoke the PrintHello class above.
public class RunIt{  public static void main (String args [])  {    PrintHello p = new PrintHello ();    p.run ();  }}
Executing the program displays the message “Hello world” 100 times. Suppose, however, the RunIt class was really very complicated and you wished to display the message as before, but while performing other initializations in the main() method. That is, the “Hello world” message would display while the program continued to work in the background. As written, this is not possible?any instructions after the call to the run() method will not execute until after the run() method terminates. However, by implementing threads, we can solve this problem.

The easiest way to create a new thread is to derive a class from java.lang.Thread. The code below is a modified version of the PrintHello class from above. It exposes a method that loops from 0 to 100, printing “Hello world” on each iteration.
public class PrintHello extends Thread{  public void run ()  {    for (int i = 0; i < 100; i++)      System.out.println ("Hello world");  }}
This class is not significantly different from the first one, yet it will still compile and run exactly as before. This proves that a Thread class exists, but as yet, the code is not multithreaded.

The second class must now be altered so that it invokes the PrintHello class in a different manner. Rather than call its run() method, RunIt will now call a start() method.
public class RunIt{  public static void main (String args [])  {    PrintHello p = new PrintHello ();    p.start ();  }}
Again, the program compiles and generates the same output as before. Hence, it may be safely concluded that the Thread class contains a start method that somewhere invokes a method called run(). Under the covers, though, the program does not work the same as before, because a second thread has actually been completed, and had any further instructions occurred in RunIt they would have executed simultaneously.The Start, Run, and Stop Methods
The Thread class defines a method called start. This method will create a brand new thread, which then runs a method called run. After the run method completes, the Thread class will tidy up and terminate the thread safely. The start method returns control to the calling routine almost immediately, and the thread runs in parallel with the remainder of the code being executed.

In some ways, the start method could be considered the thread equivalent of a main method. Parameters cannot be passed to it, however, and so the threaded class must be programmed to receive any required parameters either through the constructor or by a special method, executed before the call to start. It often is beneficial to pass a reference to the parent class as a means of providing communication from the thread to the rest of the project.

The only remaining method of significance from java.lang.Thread is stop(), which is used to terminate an executing thread. This method may be called from any class that wishes to destroy the thread and that has a reference to it. (See the sidebar “More on the Stop Method.”)

Taking Threads Farther
As can be seen, the Thread class is very easy to derive from and use. The example may be simple, but it is easy to conceive many ways that threads can be used. Imagine if a Web server didn’t farm out incoming requests to new threads, and Web page requests had to be processed one at a time!

Several years ago I developed a system to analyze texts. In this system, a lot of processing was performed without requiring user assistance. As a consequence, users were effectively prevented from clicking any buttons (such as “Help,” “About,” etc.), as the system was so busy. By moving the main loop of the program into a separate thread?which allowed the user interface to get some CPU time?I was able to reinstate the use of other events without affecting the program’s logic or its results.

At that point, I was able to leverage threads in many ways to improve the system. For example, in the original application, a particular class created a window that took some time to draw and hence was slow to appear. This too was moved into its own thread, and, although it didn’t draw any faster, it permitted the user to perform other actions while the class created its window silently in the background.

I used other threads to receive incoming messages via TCP/IP sockets?one for user messages and another for system commands. This permitted information to be silently retrieved from the system while still servicing the user.

The usefulness of threads has no end. A thread may be used to simulate a timer?the thread simply sleeps for the duration of a specified time interval, and then finally notifies other threads that the timer has expired, for example.

The flexibility of threads in Java and the ease with which they are created gives further testimony to the usefulness and elegance of Java.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time