2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
Service Oriented Architecture (SOA) has been discu...
TOP THREE LINKS YOU MUST CLICK ON


Java Basics: Introduction to Java Threads, Part 1
Yakov Fain's popular online tutorial series continues. This lesson he discusses the basics of threads, including how to create them, how to get them to step aside, and how to stop them.
Reader Feedback: Page 1 of 1

Jeff, the article states:
"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"

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.
The fact that you cannot type in the text field is absolutely not related to the fact that the "loop exclusively takes all processor''s time", but more to Swing''s architecture.
For further info, read the links I gave. They will explain the Swing "freeze" problem (the author refer to it as "the window is locked"), and the Swing architecture as well.

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!

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.
For interested readers, since those resources are not mentioned by your article, here are the links:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html

Another good reference for Swing threading is this:
http://foxtrot.sourceforge.net/
especially here:
http://foxtrot.sourceforge.net/docs/toc.php

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.

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.
But again, I just try to explain one Java feature at a time...

Hi,
while I understand this is a simple example and an introductory article on threads, I am surprised by the errors it contains.
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. Furthermore, it is proposed as a solution to move the code in another thread, which is even worse (see previous point).
Third, it is possible to start more than one worker but the example does not seem to handle this situation.
Fourth, as already noted by Marc, catching an InterruptedException without re-interrupting the current thread is bad practice.

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.
Correcting things lately will always be too late, and when people will violate Swing''s single thread rule as a normal coding style, they will always have the justification that they read an article that did so. Not good.

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 :)

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.*;
import java.awt.event.*;
import javax.swing.*;

public class ThreadStopSample extends JFrame implements ActionListener, Runnable {

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 (worker != null && worker.isAlive()) {
worker.interrupt();
} else {
worker = new Thread(this);
worker.start();
}
}

public void run() {
int i = 0;
while (true) {
try {
this.setTitle("i=" + i);
i++;
Thread.sleep(1);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}

public static void main(String[] args) {
ThreadStopSample myWindow = new ThreadStopSample();
myWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
myWindow.setBounds(0, 0, 150, 100);
myWindow.setVisible(true);
}

}


FEATURED WHITE PAPERS
YOUR FEEDBACK
Kevin Epstein wrote: Come on Maureen, I miss your incisive style and analysis here. Perhaps I'm missing something, but isn't Cassatt a bit late to the party? Where's the "news" in their announcement? Specifically, their announcement appears to be about an upcoming product... but 24 hours prior, Scalent Systems, Red Hat...
chinzip wrote: Hi Grey Flurry, any idea where can we get the codes of this articles? THanks.
Mark Blafkin wrote: IBM's 'newfound principles" may be basically supported by the closed online discussion they sponsored, but they are undoubtedly "inspired" by profit and an effort to regain their stranglehold on standards bodies. If they really cared about improving standards bodies for all stakeholders, they wouldn...
Roberto Campione wrote: Good article, that helped alot. Out of interest - have you any examples of importing templates using xmlaccess?
Java Consultant wrote: Good Post.... Java Developer...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SYS-CON FEATURED WHITEPAPERS

BREAKING WEBSPHERE NEWS
The Norwegian oil and gas giant StatoilHydro has signed a long-term agreement for IBM (NYSE: IBM) to...
The reason why ex-IBM executive Mark Papermaster can’t work for Apple is because Apple and IBM com...
IBM is going to buy Transitive, the British cross-platform virtualization firm that salvaged legacy ...
Emulex has announced that its LightPulse LP21000 family of Fibre Channel over Ethernet (FCoE) Conver...
Mark Papermaster, the ex-VP of blade development at IBM and the guy that IBM stopped from going to A...
A round-up of the many themes and topics of interest to infrastructure architects, developers and IT...
Okay, here's the deal. When you observe the big software guys and see how quickly they adopt emergin...
"More than a half dozen conferences and events targeting Virtualization and Cloud Computing canceled...
SYS-CON Events announced today that more than 40 Cloud technology providers, as well as Virtualizati...
Cloud Computing offers significant benefits over traditional solutions for deploying production syst...
IBM has found something else to do with Linux. Its Lotus software operation is going into the hardwa...
Well it appears that non-compete agreements may carry a bit more weight in New York than they do in ...
HP has said it doesn’t want to be in the cloud business itself – merely sell gear to cloud maker...
Further demonstrating continued evidence that the SAP ecosystem strategy delivers additional choices...
Cloud Computing is now an all-encompassing IT paradigm with tremendous focus on the so-called "Publi...
This is the sentence that screams "We don't get it, we don't get it, someone please help us, we don'...
SYS-CON Events announced today that the leading global virtualization technology provider VMware nam...
SYS-CON Events announced today that the leading global virtualization technology provider VMware nam...
To create application and workload best practices, Mellanox, Dell, and AMD have provided a new Dell ...
NetSuite, Larry Ellison’s other company, the on-demand one usually seen as a foil for Salesforce.c...
XML end-to-end architectures are a natural follow-on to SOA: XML for the user interface, XML for dat...
ADS BY GOOGLE