<?xml version="1.0" encoding="ISO-8859-1"?>

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
	<channel>
		<title>Java Programming Forum - Learn Java Programming - Blogs - Thread</title>
		<link>http://www.java-forums.org/blogs/thread/</link>
		<description>Java Programming Forum - Learning Java easily</description>
		<language>en</language>
		<lastBuildDate>Fri, 24 May 2013 09:40:38 GMT</lastBuildDate>
		<generator>vBulletin</generator>
		<ttl>60</ttl>
		<image>
			<url>http://www.java-forums.org/images/misc/rss.jpg</url>
			<title>Java Programming Forum - Learn Java Programming - Blogs - Thread</title>
			<link>http://www.java-forums.org/blogs/thread/</link>
		</image>
		<item>
			<title>Using threads in Java applications</title>
			<link>http://www.java-forums.org/blogs/thread/1143-using-threads-java-applications.html</link>
			<pubDate>Tue, 03 Apr 2012 09:57:00 GMT</pubDate>
			<description>Are you going to code a Java application that processes multiple tasks at the same time? Or is your program doing some heavy operations in the...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">Are you going to code a Java application that processes multiple tasks at the same time? Or is your program doing some heavy operations in the background, while the user is viewing a chart report? Such applications are referred as multi-threaded or concurrency programs. The Java platform has built-in support for threading from its very early versions, so developing multi-threaded applications in Java is not tough at all, thanks to the comprehensive and powerful threading and concurrency API.<br />
<br />
This article will walk you from fundamental concepts of thread to apply the API for Java applications that need multi-threaded capability.<br />
<br />
<br />
<b><font size="3">What is a thread?</font></b><br />
<br />
A thread is a flow of execution within a program. It is perhaps, the smallest unit of execution, beside process – an execution unit of a program. Generally, a program may consist of many processes, and each process may be divided into multiple threads.<br />
The execution of any program always runs in a thread at least, whether you notice or not. For example, in Java, the main() method is always executed by a thread; a web server processes a user’s request in a separate thread, etc. Many threads may be executed simultaneously within a program.<br />
<br />
So, threads always exist in a running program, even you have never created one explicitly.<br />
<br />
<br />
<b><font size="3">Benefit of using threads</font></b><br />
<br />
Multi-threaded applications have many advantages, here to name a few:<br />
<br />
<ul><li style="">    For desktop applications, multi-threads keep the user interface responsive while doing some lengthy tasks in the background.</li><li style="">    A server application can serve many users’ requests at the same time.</li><li style="">    For batch processing programs, multi-threads help reducing processing time and increasing productivity.</li></ul><br />
<br />
However, while developing multi-threaded applications, developer should take care of synchronization of resources which are shared among threads to avoid inconsistent state of data, dead-locking, …<br />
<br />
<br />
<b><font size="3">Java API for threads</font></b><br />
<br />
To work with threads, you should be familiar with the Thread class and the <span style="font-family: Courier New"><font size="2">Runnable</font></span> interface. They are the core class and interface which reside in the <span style="font-family: Courier New"><font size="2">java.lang</font></span> package. Though the Java platform deserves a separate package for concurrency, <span style="font-family: Courier New"><font size="2">java.util.concurrent</font></span>, it is broader than scope of this article.<br />
<br />
<b>The <span style="font-family: Courier New"><font size="2">Runnable</font></span> interface</b><br />
<br />
This interface defines a requirement for implementing objects that wish to execute code in a separate thread. It defines only one method, <span style="font-family: Courier New"><font size="2">run()</font></span>, which must be overridden by sub classes. Any code can be placed inside the <span style="font-family: Courier New"><font size="2">run()</font></span> method, and the Java Virtual Machine will call this method when it executes the thread.<br />
<br />
<br />
<b>The <span style="font-family: Courier New"><font size="2">Thread</font></span> class</b><br />
<br />
This is the core class that represents a thread of execution in a Java program, it implements the <span style="font-family: Courier New"><font size="2">Runnable</font></span> interface. Your code must be placed inside (or call from) its <span style="font-family: Courier New"><font size="2">run()</font></span> method in order to be executed in a separate thread. The class has many constructors, however following are the three commonly used ones:<br />
<br />
<ul><li style=""><span style="font-family: Courier New"><font size="2">Thread()</font></span>: this no-argument constructor simply creates a new <span style="font-family: Courier New"><font size="2">Thread</font></span> object with all defaults.<br /></li><li style="">        <span style="font-family: Courier New"><font size="2">Thread(String name)</font></span>: creates new <span style="font-family: Courier New"><font size="2">Thread</font></span> object with the given name.<br /></li><li style=""><span style="font-family: Courier New"><font size="2">Thread(Runnable target)</font></span>: creates a new <span style="font-family: Courier New"><font size="2">Thread</font></span> object which wraps a <span style="font-family: Courier New"><font size="2">Runnable</font></span> object.</li></ul><br />
<br />
<br />
Some important methods are:<br />
<br />
<ul><li style=""><span style="font-family: Courier New"><font size="2">run()</font></span>: this is the most important method, subclasses must override this method and code inside this method will be executed in a thread.<br /></li><li style=""><span style="font-family: Courier New"><font size="2">start()</font></span>: starts execution of the thread, the run() method will be called.<br /></li><li style=""><span style="font-family: Courier New"><font size="2">sleep(long millis)</font></span>: causes current thread to be paused temporarily for a specified time in milliseconds. This is a static method.<br /></li><li style=""><span style="font-family: Courier New"><font size="2">join()</font></span>: causes the calling thread waits for this thread to finish execution.<br /></li><li style=""><span style="font-family: Courier New"><font size="2">interrupt()</font></span>: wakes up this thread if it is sleeping or waiting, an InterruptedException will be thrown.</li></ul><br />
<br />
<br />
<b><font size="3">Life cycle of a thread</font></b><br />
<br />
Typically, a thread can be in one of the following states:<br />
<br />
<div style="text-align: center;"><img src="http://www.java-forums.org/attachments/java-software/3399d1333447729-lince-1-0-thread-life-cycle.png" border="0" alt="Name:  thread life cycle.png
Views: 1205
Size:  5.6 KB" class="thumbnail" style="float:CONFIG" /><br />
<b>Figure: Life cycle of a thread</b></div><br />
<ul><li style="">    <i>New</i>: when an instance of a <span style="font-family: Courier New"><font size="2">Thread</font></span> is created and it has not been started yet.</li><li style="">    <i>Runnable</i>: when the <span style="font-family: Courier New"><font size="2">start()</font></span> method has been called, and the <span style="font-family: Courier New"><font size="2">run()</font></span> method has not been executed. It’s up for the JVM to decide when to call <span style="font-family: Courier New"><font size="2">run()</font></span> method, even when the <span style="font-family: Courier New"><font size="2">start()</font></span> method is called.</li><li style="">    <i>Running</i>: when the <span style="font-family: Courier New"><font size="2">run()</font></span> method is called and being executed.</li><li style="">    <i>Waiting/Blocking</i>: when the thread is going to sleep while running or it has to wait for a resource available to continue. The thread will become runnable when it exits the waiting/blocking state.</li><li style="">    <i>Dead</i>: the thread become dead when the <span style="font-family: Courier New"><font size="2">run()</font></span> method completes. A dead thread cannot be started over again.</li></ul><br />
<br />
<b><font size="3">Creating a thread</font></b><br />
<br />
There are two methods to create a thread: by subclassing the <span style="font-family: Courier New"><font size="2">Thread</font></span> class, or by implementing <span style="font-family: Courier New"><font size="2">Runnable</font></span> interface.<br />
<br />
The first method: Create a new class that extends <span style="font-family: Courier New"><font size="2">Thread</font></span> class, and override <span style="font-family: Courier New"><font size="2">run()</font></span> method:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Extending Thread class</div>

	<pre class="brush: java">public class DemoThread extends Thread {
        public void run() {
            // code executed in thread placed here...
        }

}

Thread thread = new DemoThread();</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 <br />
The second method: Create a new class that implements <span style="font-family: Courier New"><font size="2">Runnable</font></span> interface, and implement <span style="font-family: Courier New"><font size="2">run()</font></span> method:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Implementing Runnable interface</div>

	<pre class="brush: java">public class DemoThread implements Runnable {
        public void run() {
            // code executed in thread placed here...
        }

}
    Runnable runnable = new DemoThread();
    Thread thread = new Thread(runnable);</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 So, what’s difference? Well, it’s all about flexibility. With the first method, the implementing class can change behavior of the <span style="font-family: Courier New"><font size="2">Thread</font></span> class, such as providing custom implementation for some methods, or creating a wrapper class. However, the implementing class will not be able to extend another class (because Java does not allow multiple inheritances). With the second one, you are free to let your class extends another class while still keeping behavior of a thread. It’s up to you to decide which method to follow, however the latter method is preferred in practice, since it’s more flexible.<br />
<br />
<br />
<b><font size="3">Starting a thread</font></b><br />
<br />
Just call the <span style="font-family: Courier New"><font size="2">start()</font></span> method of the <span style="font-family: Courier New"><font size="2">Thread</font></span> class:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Start a thread</div>

	<pre class="brush: java">thread.start();</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 Then the JVM will call <span style="font-family: Courier New"><font size="2">run()</font></span> method and execute the code inside <span style="font-family: Courier New"><font size="2">run()</font></span> method in a separate thread. When the <span style="font-family: Courier New"><font size="2">run()</font></span> method completes, the thread become die. If the <span style="font-family: Courier New"><font size="2">start()</font></span> method is invoked again, an <span style="font-family: Courier New"><font size="2">IllegalThreadStateException</font></span> will be thrown.<br />
<br />
<br />
<b><font size="3">Using sleep(), join() and interrupt()</font></b><br />
<br />
The following code snippet demonstrates using of <span style="font-family: Courier New"><font size="2">sleep()</font></span> method. The current thread pauses for 10 seconds for each loop:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Using sleep() method</div>

	<pre class="brush: java">public class DemoThread extends Thread {
    public void run() {
        while (true) {
           
            // do something here...
           
            try {
                Thread.sleep(10000);    // sleep for 10 seconds
            } catch (InterruptedException ex) {
                // interrupted, exits sleep state
            }
        }
    }
   
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 The <span style="font-family: Courier New"><font size="2">sleep()</font></span> method is static, so calling it will affect the currently running thread. The exception InterruptedException is thrown when this thread is interrupted when the <span style="font-family: Courier New"><font size="2">interrupt()</font></span> method is invoked on this thread object.<br />
<br />
When the <span style="font-family: Courier New"><font size="2">join()</font></span> method is invoked on a thread, the calling thread will wait for the called thread to finish. In the following example, the main thread (the thread that executes the <span style="font-family: Courier New"><font size="2">main()</font></span> method) will wait for the thread thread1 to finish, then the main thread continue its execution:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Using join()</div>

	<pre class="brush: java">public class DemoThread extends Thread {
    public void run() {
        while (true) {
           
            // do something here...
           
            try {
                Thread.sleep(10000);    // sleep for 10 seconds
            } catch (InterruptedException ex) {
                // interrupted, exits sleep state
            }
        }
    }
   
    public static void main(String... args) {
        Thread thread = new DemoThread();
        System.out.println(&quot;It's the thread's turn&quot;);
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException ex) {
            // interrupted while waiting
        }
        System.out.println(&quot;It's my turn&quot;);
    }
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 So when does <span style="font-family: Courier New"><font size="2">join()</font></span> need to be called? Well, when the calling thread needs to process something done by the called thread, so it has to wait for the called thread done processing. Otherwise, if not using <span style="font-family: Courier New"><font size="2">join()</font></span>, the calling thread is still running in parallel with the called thread, so it my access the data in wrong state.<br />
<br />
The <span style="font-family: Courier New"><font size="2">interrupt()</font></span> method is often called to interrupt a currently sleeping/waiting thread. For example, in the following code, when the thread is sleeping, it will be woke up and exits the while loop if an <span style="font-family: Courier New"><font size="2">interrupt()</font></span> is called:<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code: Using sleep() method</div>

	<pre class="brush: java">
    public void run() {
        while (true) {
           
            // do something here...
           
            try {
                Thread.sleep(10000);    // sleep for 10 seconds
            } catch (InterruptedException ex) {
                // interrupted, exits sleep state
            }
        }
    }
   
    // another thread interrupts

    thread.interrupt();</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 <br />
Calling <span style="font-family: Courier New"><font size="2">interrupt()</font></span> will thrown an <span style="font-family: Courier New"><font size="2">InterruptedException</font></span> to the sleeping/waiting thread. However, it does not have any effect for a running thread (not sleeping/waiting).<br />
<br />
<br />
<b><font size="3">Synchronization issue</font></b><br />
<br />
Problems might be occurred when multiple threads accessing a same object, such as inconsistent state of an object being modified/accessed by many threads concurrently. To address the problem, Java introduces <span style="font-family: Courier New"><font size="2">synchronized</font></span> keyword. When a method or a code block is marked with <span style="font-family: Courier New"><font size="2">synchronized</font></span> keyword, the method or code block can be accessed by only one thread at a time, thus eliminates the inconsistent state problem. Though this article is not focusing on synchronization topic, the synchronization issue should be taken care of when developing multi-threaded applications.<br />
<br />
<br />
<b><font size="3">Threading in Swing</font></b><br />
<br />
Java’s Swing framework is single-threaded, that means Swing’s UI components can be accessed by only one thread at a time. A thread is called event dispatching thread, which is the only thread that can access Swing components. So the Java API provides the <span style="font-family: Courier New"><font size="2">SwingUtilities</font></span> class with two static methods which should be used when using multiple threads in Swing:<br />
<br />
<ul><li style="">    <span style="font-family: Courier New"><font size="2">SwingUtilities.invokeLater(Runnable doRun)</font></span>: executes the code in the event dispatching thread, the method returns immediately.</li><li style="">    <span style="font-family: Courier New"><font size="2">SwingUtilities.invokeAndWait(Runnable doRun)</font></span>: executes the code in the event dispatching thread, but the method has to wait for the code to execute.</li></ul><br />
<br />
<br />
So remember to use those two methods when using threads in Swing applications.<br />
<br />
<br />
<b><font size="3">Methods are no longer used</font></b><br />
<br />
Some of the methods in Thread class are deprecated, so using them is greatly discouraged. These methods are: <span style="font-family: Courier New"><font size="2">destroy(), resume(), stop(), suspend()</font></span>. Consult the Java API documentation for more details.<br />
<br />
<br />
<b><font size="3">Conclusion</font></b><br />
<br />
The Java platform has built-in great support for threading, however there are some notices should be considered when developing multi-threaded applications: the synchronization issue, the Swing’s single thread model, and the deprecated methods.</blockquote>

]]></content:encoded>
			<dc:creator>Thread</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/thread/1143-using-threads-java-applications.html</guid>
		</item>
		<item>
			<title>Thread communication</title>
			<link>http://www.java-forums.org/blogs/thread/770-thread-communication.html</link>
			<pubDate>Sun, 08 Jan 2012 11:18:23 GMT</pubDate>
			<description>Following methods are used to perform communication between threads. 
 
•	Wait() 
•	Notify() 
•	notifyAll() 
 
In the following code, count is a...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">Following methods are used to perform communication between threads.<br />
<br />
<div style="margin-left:40px">•	Wait()<br />
•	Notify()<br />
•	notifyAll()</div><br />
In the following code, count is a shared variable between different threads. It’s a consumer producer process in which consumer waits in consume() method and waits for producer to perform its action.<br />
<br />
<div style="text-align: center;"><img src="http://www.java-forums.org/attachments/java-software/2593d1326021469-trackstudio-enterprise-3-5-16-62.jpg" border="0" alt="Name:  62.JPG
Views: 345
Size:  26.1 KB" class="thumbnail" style="float:CONFIG" /><br />
<br />
<b>Thread communication</b></div></blockquote>

]]></content:encoded>
			<dc:creator>Thread</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/thread/770-thread-communication.html</guid>
		</item>
		<item>
			<title>High-level thread states</title>
			<link>http://www.java-forums.org/blogs/thread/769-high-level-thread-states.html</link>
			<pubDate>Sun, 08 Jan 2012 11:16:33 GMT</pubDate>
			<description>Following diagrams display different thread states. 
 
Attachment 2592 (http://www.java-forums.org/attachments/java-software/2592-scala-2-5-0-final-62.jpg) 
 
*Thread...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">Following diagrams display different thread states.<br />
<br />
<div style="text-align: center;"><img src="http://www.java-forums.org/attachments/java-software/2592d1326021349-scala-2-5-0-final-62.jpg" border="0" alt="Name:  62.JPG
Views: 495
Size:  29.7 KB" class="thumbnail" style="float:CONFIG" /><br />
<br />
<b>Thread States</b></div><br />
•	Runnable: Thread in this state is waiting for its turn to start execution.<br />
•	Running: Thread is executing and performing its functionality. <br />
•	Waiting: Thread is in blocked state and waiting for some operation to finish.<br />
•	Sleeping: Thread is suspended forcefully. <br />
•	Blocked on I/O: Thread will start execution after completion of I/O<br />
•	Blocked on synchronization: Thread will move to Runnable when a lock is acquired.<br />
•	Dead: Thread has completed working.</blockquote>

]]></content:encoded>
			<dc:creator>Thread</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/thread/769-high-level-thread-states.html</guid>
		</item>
		<item>
			<title>Thread Creation</title>
			<link>http://www.java-forums.org/blogs/thread/768-thread-creation.html</link>
			<pubDate>Sun, 08 Jan 2012 11:12:42 GMT</pubDate>
			<description>Threads can be created using one of the following methods. 
 
•	By Extending Thread class. 
•	By Implementing Runnable interface. 
 
 
 
class...</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">Threads can be created using one of the following methods.<br />
<br />
•	By Extending Thread class.<br />
•	By Implementing Runnable interface.<br />
<br />
<div class="bbcode_container">
	<div class="bbcode_description">Java Code:  Thread creation</div>

	<pre class="brush: java">
class Counter extends Thread {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let’s see how to start the threads
public static void main(String&#91;&#93; args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd thread. This calls the run() method
}
}

class Counter extends Base implements Runnable {
//method where the thread execution will start
public void run(){
//logic to execute in a thread
}
//let us see how to start the threads
public static void main(String&#91;&#93; args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd thread. This calls the run() method
}
}</pre>
	<script type="text/javascript">mh_sh_highlight_all('java');</script>

</div>
 </blockquote>

]]></content:encoded>
			<dc:creator>Thread</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/thread/768-thread-creation.html</guid>
		</item>
		<item>
			<title>Processes vs Threads</title>
			<link>http://www.java-forums.org/blogs/thread/767-processes-vs-threads.html</link>
			<pubDate>Sun, 08 Jan 2012 11:10:18 GMT</pubDate>
			<description>Thread is a single execution in a process as compared to process which is an execution of a program. A process may have multiple threads within it....</description>
			<content:encoded><![CDATA[<blockquote class="blogcontent restore">Thread is a single execution in a process as compared to process which is an execution of a program. A process may have multiple threads within it. Also a thread is sometime referred as lightweight process. All the threads in JVM share heap that belongs to the process. In this case, different threads can access same object. Threads always share the heap and contain their own stack to store local variables. In this way threads are kept thread-safe and are synchronized.<br />
<br />
<div style="text-align: center;"><img src="http://www.java-forums.org/attachments/java-software/2589d1326020979-languagetool-0-9-62.jpg" border="0" alt="Name:  62.JPG
Views: 1311
Size:  26.7 KB" class="thumbnail" style="float:CONFIG" /><br />
<br />
<b>Processes vs Threads</b></div></blockquote>

]]></content:encoded>
			<dc:creator>Thread</dc:creator>
			<guid isPermaLink="true">http://www.java-forums.org/blogs/thread/767-processes-vs-threads.html</guid>
		</item>
	</channel>
</rss>
