Welcome!

Java Authors: Carmen Gonzalez, Jim Kaskade, Aater Suleman, Pat Romanski, Paige Leidig

Related Topics: Java

Java: Article

Java Basics: Introduction to Java Threads, Part 1

Lesson 8, Java Basics

A program can perform its actions either in a sequence (one after another) or in parallel. In a sequential mode, if a program needs to call two methods of a class, the second method is called after the first one completes. In other words, such programs have only one thread of execution. In some cases, when a second method does not depend on the results of the first one, you can substantially speed up the processing by executing these methods at the same time in a multi-threaded mode.

A good example of a program that creates multiple threads is your Web browser. You can browse the Internet while downloading some files - one program runs two threads of execution. If these two tasks would have run sequentially, the browser's screen would have been frozen until the download is complete. In case of a one-processor computer, each thread gets a slice of the processor's time. Since this happens pretty fast, a user can't notice small delays. If you run a multi-threaded program on a computer that has two or more processors, performance of such program can be increased dramatically.

Multi-threading is used in most of the graphical games: while one thread displays GUI components on the screen, the second thread calculates coordinates of the next image based on the player's move.

A Sample Program Without Threads

When I teach classes, I usually start with some theory and then show sample programs to illustrate the subject, but in this case I believe it's better to start by writing two very simple programs to give you a better feeling of why threads are needed. I'll give you some explanations as we go.

 Each of these sample programs will use Swing components - a button and a text field. When a user hits the button Kill Time, the program starts a loop that increments a counter thirty thousand times. The current value of the variable-counter will be displayed on the title bar of the window. The class NoThreadsSample has only one thread of execution and you won't be able to type anything in the text field until the loop is done. This loop exclusively takes all processor's time, that's why the window is locked.

For those of you who did not have a chance to create GUI screens with Swing, let me just say that the constructor of the class NoThreadsSample creates a button and a text field and registers this class with so called ActionListener that will process button clicks. Whenever a user clicks on the button, JVM will call the method actionPerformed(), and we start our kill-time-loop there. This class is inherited from JFrame that comes with Swing and the ActionListener interface is needed for this program to process clicks on the button.


import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class NoThreadsSample extends JFrame implements ActionListener{
  // Constructor
  NoThreadsSample(){
  // Create a frame with a button and a text field
	GridLayout gl =new GridLayout(2,1);
	this.getContentPane().setLayout(gl);
	JButton myButton = new JButton("Kill Time");
	myButton.addActionListener(this);
	this.getContentPane().add(myButton);
	this.getContentPane().add(new JTextField());
  }
  // Process button clicks
  public void actionPerformed(ActionEvent e){
  // Just  kill some time to show
  // that window controls are locked
    	for (int i=0; i<30000;i++){
    	  this.setTitle("i="+i);
    	}
    }

  public static void main(String[] args) {
    // Create an instance of the frame
    NoThreadsSample myWindow = new NoThreadsSample();
    // Ensure that the window can be closed
    // by pressing a little cross in its corner
    myWindow.setDefaultCloseOperation(
	  WindowConstants.EXIT_ON_CLOSE);

    // Set the frame's size - top left corner
    // coordinates, width and height
	myWindow.setBounds(0,0,150, 100);
    //Make the window visible
    myWindow.setVisible(true);
  }
}

Compile and run this class and see for yourself that the window is locked for some time and that you can't use the text field until the loop is over.

Re-writing our Sample Program With Threads

The next version of this little window will create and start a separate thread for the loop, and the main window's thread will allow you to type in the text field.

In Java, you can create a thread using one of the following ways:

1.  Create an instance of the Java class Thread and pass to this instance an object that implements Runnable interface. For example, if a class SomeGameProcessor implements Runnable interface the code may look as follows:


SomeGameProcessor sgp = new SomeGameProcessor();
Thread worker = new Thread(sgp);

The Runnable interface requires that a class has to implement the code that must be running as a separate thread in the method run(). But to start the thread, you have to call the Thread's method start(), that will actually call your method run(). I agree, it's a bit confusing, but this is how you start a thread:


worker.start();

2.  Create a subclass of the class Thread and implement the method run() there. To start the thread call the method start().


public class MyThread extends Thread{

  public static void main(String[] args) {
	MyThread worker = new MyThread();
	worker.start();
  }
  public void run(){
    // your code goes here
  }
}

In my class ThreadsSample I'll create a thread using the first method because this class already extends JFrame, and you can't inherit a Java class from more than one parent.


import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ThreadsSample extends JFrame
             implements ActionListener, Runnable{

  // Constructor
  ThreadsSample(){
   // Create a frame with a button and a text field
	GridLayout gl =new GridLayout(2,1);
	this.getContentPane().setLayout(gl);
	JButton myButton = new JButton("Kill Time");
	myButton.addActionListener(this);
	this.getContentPane().add(myButton);
	this.getContentPane().add(new JTextField());
  }

  public void actionPerformed(ActionEvent e){
  // Create a thread and execute the kill-time-code
  // without blockiing the window
    Thread worker = new Thread(this);
    worker.start();  // this calls the method run()
  }

  public void run(){
  // Just  kill some time to show that
  // window controls are NOT locked
	for (int i=0; i<30000;i++){
  	  this.setTitle("i="+i);
	}
   }

  public static void main(String[] args) {

	ThreadsSample myWindow = new ThreadsSample();
  // Ensure that the window can be closed
  // by pressing a little cross in the corner
  	myWindow.setDefaultCloseOperation(
	       WindowConstants.EXIT_ON_CLOSE);

  // Set the frame's size and make it visible
	myWindow.setBounds(0,0,150, 100);
	myWindow.setVisible(true);
  }
}

The class ThreadsSample starts a new thread in the method actionPerformed(), which is called whenever you click on the button Kill Time. After this, the thread with a loop and the main thread take turns in getting slices of the processor's time. Now you can type in the text field (the main thread), while the other thread runs the loop! Try it out.

After calling the method worker.start(), our program does not wait until the code in the method run() completes, but runs this code in a separate thread of execution. Since the GUI part runs in a different thread, the screen is not locked.

Note - There are special requirements for using Java threads in Swing, and you can find more here: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

Sleeping Threads

One of the ways for a tread to step aside and let the processor continue working with other threads is by using the method sleep()of the class Thread. This method takes one parameter that specifies (in milliseconds) how log the thread has to sleep. For example, if your program needs to refresh the screen with stock quotes every five seconds (see an example of how to get stock quotes in the lesson Reading Data from the Internet), you can do it like this:

  public void run(){

  try{
   while (true)
     // call the code that gets the price quote here
     // and display the current price of the stok(s)
     sleep (5000);  // sleep for 5 second
   }
  }catch(InterruptedException e ){
    System.out.println(Thread.currentThread().getName()
	  + e.toString());
  }
}   

In our endless loop this thread will "wake up" every five seconds, execute the code that gets the stock quote and will go to sleep again for another five seconds. The method sleep() may throw the InterruptedException, that's why we handle it in a try/catch block. A thread can be interrupted not only because of an error condition, but a program can try to interrupt a running thread by calling its method interrupt:


worker.interrupt();

How to Stop a Thread

Ideally, a thread should die after completing the code in its method run(). But what if you'd like to stop it earlier? The class Thread has a method stop() that was deprecated a long time ago, because in some cases it was making programs unstable (the methods suspend() and resume() were deprecated as well). I'm not planning to elaborate on this topic here, but you can read about this at the following Web page : java.sun.com/j2se/1.5.0/docs/guide/misc/ threadPrimitiveDeprecation.html.

So, we need to find some other way to stop unwanted threads.

The class ThreadStopSample is a slightly modified version of the class ThreadsSample, and it will show you how to stop a thread by declaring a flag variable and setting it to true when the thread has to be killed. We declare a boolean variable stopThreadFlag and the GUI button will work as a toggle to start or stop the thread. The method actionPerformed(), is called whenever the user clicks on the button, and we check there if the thread is currently running ( the method Thread.isAlive() returns true), and set the stopThreadFlag to true in this case. On the other hand, the code in the method run() is enclosed in the loop while (!stopThreadFlag). As soon as the variable stopThreadFlag is set to true, the loop (read Thread) will end.


import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ThreadStopSample extends JFrame
              implements ActionListener, Runnable{

   private volatile boolean stopThreadFlag = false;
   Thread worker=null ;

    // Constructor
   ThreadStopSample(){
	// Create a frame with a button and a text field
	GridLayout gl =new GridLayout(2,1);
	this.getContentPane().setLayout(gl);
	JButton myButton = new JButton("Start/Stop Thread");
	myButton.addActionListener(this);
	this.getContentPane().add(myButton);
	this.getContentPane().add(new JTextField());
   }

    public void actionPerformed(ActionEvent e){
    	// If the thread is running, turn the flag to stop it.
    	// Otherwise, start the thread
        if (worker!=null && worker.isAlive()){
        	setStopThreadFlag(true);
        }else{
        	setStopThreadFlag(false);
        	worker = new Thread(this);
        	worker.start();  // this calls the method run()
        }

    }

    public void run(){
       // Run the thread until the stop flag is on
       int i=0;
       while (!stopThreadFlag){
		this.setTitle("i="+i);
		i++;
       }
    }

     public void setStopThreadFlag(boolean flag)
    {
    	 stopThreadFlag = flag;
    }

    public static void main(String[] args) {
	// Create an instance of the frame
	ThreadStopSample myWindow = new ThreadStopSample();
	// Ensure that the window can be closed
	// by pressing a little cross in the corner
	myWindow.setDefaultCloseOperation(
	         WindowConstants.EXIT_ON_CLOSE);

	// Set the frame's size ang make it visible
	myWindow.setBounds(0,0,150, 100);
	myWindow.setVisible(true);
   }

}

Please note that the variable stopThreadFlag is declared as volatile. This is done to make sure that if the value of this variable is changed by one of the threads in a multi-threaded application, the running thread will see its latest value. This basically forces JVM to always refresh the local copies of such variables, i.e. in a CPU register

Our method run() just increments the counter, but in real-world applications a running thread may use some other resources, for example work with files, databases, or maintain connections to remote computers. When you stop such thread, make sure that it closes all opened resources - the finally clause of the try block is the right place to do this (see the lessons on working with streams).

Threads are used in most of the Java applications one way or the other. Either your program explicitly creates and handles threads, or an application server where your program may be deployed can create multiple threads without any additional programming required on your part. For example, hundreds of users may work at the same time with an online store that may be implemented as a Web application using Java Servlets. Each user's request will be processed by the same servlet, but the servlet container will create a separate thread of execution for each of these requests.

In this lesson you've learned the basics of threads. In a follow up article I'll show you how to create a more useful multi-threaded program than our kill-time sample.

More Stories By Yakov Fain

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

Comments (7)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Harbinger Systems will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Harbinger Systems is a global company providing software technology services. Since 1990, Harbinger has developed a strong customer base worldwide. Its customers include software product companies ranging from hi-tech start-ups in Silicon Valley to leading product companies in the US and large in-house IT organizations.
SYS-CON Events announces a new pavilion on the Cloud Expo floor where WebRTC converges with the Internet of Things. Pavilion will showcase WebRTC and the Internet of Things. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices--computers, smartphones, tablets, and sensors – connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo & @ThingsExpo are the leading events covering the booming market of Cloud Computing, IoT & Big Data for the enterprise. Speakers from all over the world will be hand-picked for their ability to explore the economic strategies that utility/cloud computing provides. Whether public, private, or in a hybrid form, clo...
SYS-CON Events announced today that Gridstore™, the leader in software-defined storage (SDS) purpose-built for Windows Servers and Hyper-V, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Gridstore™ is the leader in software-defined storage purpose built for virtualization that is designed to accelerate applications in virtualized environments. Using its patented Server-Side Virtual Controller™ Technology (SVCT) to eliminate the I/O blender effect and accelerate applications Gridsto...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at Internet of @ThingsExpo, Andrew Bolwell, Director of Innovation for HP’s Printing and Personal Systems Group, will discuss how key attributes of mobile technology – touch input, senso...
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
Connected devices and the Internet of Things are getting significant momentum in 2014. In his session at Internet of @ThingsExpo, Jim Hunter, Chief Scientist & Technology Evangelist at Greenwave Systems, will examine three key elements that together will drive mass adoption of the IoT before the end of 2015. The first element is the recent advent of robust open source protocols (like AllJoyn and WebRTC) that facilitate M2M communication. The second is broad availability of flexible, cost-effective storage designed to handle the massive surge in back-end data in a world where timely analytics...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at Internet of @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., will show what is needed to leverage the IoT to transform your business. He will discuss opportunities and challenges ahead for the IoT from a market and tec...
SYS-CON Events announced today that TeleStax, the main sponsor of Mobicents, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. TeleStax provides Open Source Communications software and services that facilitate the shift from legacy SS7 based IN networks to IP based LTE and IMS networks hosted on private (on-premise), hybrid or public clouds. TeleStax products include Restcomm, JSLEE, SMSC Gateway, USSD Gateway, SS7 Resource Adaptors, SIP Servlets, Rich Multimedia Services, Presence Services/RCS, Diame...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An...
SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Transparent Cloud-computing Consortium (abbreviation: T-Cloud Consortium) will conduct research activities into changes in the computing model as a result of collaboration between "device" and "cloud" and the creation of new value and markets through organic data processing High speed and high quality networks, and dramatic improvements in computer processing capabilities, have greatly changed the nature of applications and made the storing and processing of data on the network commonplace.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
As a disruptive technology, Web Real-Time Communication (WebRTC), which is an emerging standard of web communications, is redefining how brands and consumers communicate in real time. The on-going narrative around WebRTC has largely been around incorporating video, audio and chat functions to apps. In his session at Internet of @ThingsExpo, Alex Gouaillard, Founder and CTO of Temasys Communications, will look at a fourth element – data channels – and talk about its potential to move WebRTC beyond browsers and into the Internet of Things.
SYS-CON Events announced today that Gigaom Research has been named "Media Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Ashar Baig, Research Director, Cloud, at Gigaom Research, will also lead a Power Panel on the topic "Choosing the Right Cloud Option." Gigaom Research provides timely, in-depth analysis of emerging technologies for individual and corporate subscribers. Gigaom Research's network of 200+ independent analysts provides new content daily that bridges the gap between break...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
The Industrial Internet revolution is now underway, enabled by connected machines and billions of devices that communicate and collaborate. The massive amounts of Big Data requiring real-time analysis is flooding legacy IT systems and giving way to cloud environments that can handle the unpredictable workloads. Yet many barriers remain until we can fully realize the opportunities and benefits from the convergence of machines and devices with Big Data and the cloud, including interoperability, data security and privacy.