SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY.
CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...| By Yakov Fain | Article Rating: |
|
| January 24, 2006 12:00 AM EST | Reads: |
143,196 |
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.
Published January 24, 2006 Reads 143,196
Copyright © 2006 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
- Your First Java Program
- Intro to Object-Oriented Programming with Java
- Methods, Constructors, Overloading and Access Levels
- Java Exceptions
- Java Streams Basics
- Reading Data from the Internet
- Java Serialization
- Teaching Kids Programming: Even Younger Kids Can Learn Java
- Java Basics: Introduction to Java Threads, Part 2
- SYS-CON Webcast: Eclipse IDE for Students, Useful Eclipse Tips & Tricks
- Java Basics: Lesson 11, Java Packages and Imports (Live Video Education)
More Stories By Yakov Fain
Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain
![]() |
Simon 08/27/04 01:55:16 PM EDT | |||
Jeff, the article states: What happens if I have a 2 CPU box ? One CPU will be 100%, but the other will be 0%, plenty of resource to type in the text field. |
||||
![]() |
Jeff 08/27/04 01:41:24 PM EDT | |||
Simon, you stated: "First of all, the single thread rule of Swing is violated (setTitle() is called from outside the event dispatch thread). This is a gross mistake, especially when there is no explanation on why it has been done. Second, it is said that the reason why it is not possible to type in the textfield is that because the CPU is 100% busy. This is clearly false, and shows bad understanding of how Swing works." Can you please explain your answers here? I''m a noob so saying something is "clearly false" without a "why" doesn''t help me. Thanks! |
||||
![]() |
Simon 08/27/04 09:21:34 AM EDT | |||
Read again - carefully this time - the article you mention, and you''ll see that your example *does* violate the single thread rule. Also, I suggest you to read the second and third continuations of the same article. Another good reference for Swing threading is this: About the catch 22 situation, I would say you shoot in your foot, since 99% of thread tutorials out there do not use Swing as a first thread example, exactly because it requires too much background. Noone forced you to use a wrong example, to talk about wrong problems (the 100% CPU thing) and to suggest wrong solutions for them. Once more, not good. It''s just unfortunate that only few readers, after reading the article, take the time to read the comments. |
||||
![]() |
Yakov 08/27/04 06:50:01 AM EDT | |||
1. Calling setTitle() from the actionPerformed is fine and does not violate Swing''s single thread rule because actionPerformed() method is automatically invoked in the dispath-thread (see http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html) 2. I agree that calling another thread from the actionPerformed() should have been done using invokeLater(), but it''s a catch 22 situation: I can''t explain this without explaining thread basics first. Probably I should have mention that Swing has its special way of working with threads. |
||||
![]() |
Simon 08/27/04 04:36:23 AM EDT | |||
Hi, I think stating right things from the beginning, especially if the goal of the article is to be an introduction to threads for people that don''t know them, is a better approach. |
||||
![]() |
Yakov 08/25/04 04:44:09 PM EDT | |||
Marc, This is a just a first light intro to threads and my sample code is written properly. At the end of the article I''ve also mentioned that you may need to close all io resources when killing a thread. Your suggestion with interrupt() may not always work with threads that have opened streams. It''s recommended to stop such threads by simple closing these streams, connections, etc. Let''s keep things simple for now :) |
||||
![]() |
Marc 08/25/04 03:48:02 PM EDT | |||
If your while loop launches more threads, or does blocking IO operations, the main thread (with the invariant while (!stopThreadFlag)) will end but you still have open resouces and other threads that may still be running. A better (albeit not as elegant) mechanism to use would be the interrupt() method. Here is a rewritten version using it. I''m sure this comment box will screw up formatting. import java.awt.*; public class ThreadStopSample extends JFrame implements ActionListener, Runnable { Thread worker = null; // Constructor public void actionPerformed(ActionEvent e) { public void run() { public static void main(String[] args) { } |
||||
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY.
CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...Jul. 4, 2018 04:45 PM EDT Reads: 4,336 |
By Pat Romanski Jul. 4, 2018 10:00 AM EDT |
By Yeshim Deniz Jul. 3, 2018 04:45 PM EDT |
By Yeshim Deniz Jul. 3, 2018 03:45 PM EDT Reads: 3,571 |
By Elizabeth White Jul. 3, 2018 11:45 AM EDT Reads: 2,278 |
By Pat Romanski Jul. 3, 2018 08:30 AM EDT Reads: 2,941 |
By Pat Romanski A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.Jul. 2, 2018 05:00 AM EDT Reads: 4,643 |
By Pat Romanski Jul. 1, 2018 05:30 PM EDT Reads: 2,281 |
By Yeshim Deniz Jul. 1, 2018 12:00 PM EDT Reads: 4,024 |
By Elizabeth White SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY.
DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.Jun. 30, 2018 07:00 PM EDT Reads: 10,447 |



A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY.
DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
The past few years have brought a sea change in the way applications are architected, developed, and consumed-increasing both the complexity of testing and the business impact of software failures. How can software testing professionals keep pace with modern application delivery, given the trends that impact both architectures (cloud, microservices, and APIs) and processes (DevOps, agile, and continuous delivery)? This is where continuous testing comes in.
Attend this session to discover why and how continuous testing is different from traditional test automation.
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical Infrastructure as a Service cloud provider but it's been des...
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the...
Hackers took three days to identify and exploit a known vulnerability in Equifax’s web applications. I will share new data that reveals why three days (at most) is the new normal for DevSecOps teams to move new business /security requirements from design into production. This session aims to enlighten DevOps teams, security and development professionals by sharing results from the 4th annual State of the Software Supply Chain Report -- a blend of public and proprietary data with expert research and analysis.Attendees can join this session to better understand how DevSecOps teams are applying...
So the dumpster is on fire. Again. The site's down. Your boss's face is an ever-deepening purple. And you begin debating whether you should join the #incident channel or call an ambulance to deal with his impending stroke. Yes, we know this is a developer's fault. There's plenty of time for blame later. Postmortems have a macabre name because they were once intended to be Viking-like funerals for someone's job. But we're civilized now. Sort of. So we call them post-incident reviews. Fires are never going to stop. We're human. We miss bugs. Or we fat finger a command - deleting dozens of server...
The DevOps Institute's vision is to facilitate a community where members have access to the most innovative, inspirational and transformational DevOps content, courses and certifications around emerging DevOps practices and principles. We strive to provide content that inspires discussion, collaboration, transformation, and to foster healthy dialogue among global members of various technical backgrounds and experiences.
Cloud is the motor for innovation and digital transformation. CIOs will run 25% of total application workloads in the cloud by the end of 2018, based on recent Morgan Stanley report. Having the right enterprise cloud strategy in place, often in a multi cloud environment, also helps companies become a more intelligent business. Companies that master this path have something in common: they create a culture of continuous innovation.
In his presentation, Dilipkumar will outline the latest research and steps companies can take to make innovation a daily work habit by using enterprise cloud comp...
The digital transformation is real! To adapt, IT professionals need to transform their own skillset to become more multi-dimensional by gaining both depth and breadth of a wide variety of knowledge and competencies. Historically, while IT has been built on a foundation of specialty (or "I" shaped) silos, the DevOps principle of "shifting left" is opening up opportunities for developers, operational staff, security and others to grow their skills portfolio, advance their careers and become "T"-shaped.
Using new techniques of information modeling, indexing, and processing, new cloud-based systems can support cloud-based workloads previously...
Adding public cloud resources to an existing application can be a daunting process. The tools that you currently use to manage the software ...



















