Welcome!

Java Authors: Esmeralda Swartz, Trevor Parsons, Sandi Mappic, Lori MacVittie, JP Morgenthal

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
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
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...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
SYS-CON Events announced today that SOA Software, an API management leader, 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. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
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 Utimaco 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. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
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...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

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 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.
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...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...