Home | Login | Blog | Forum | Download | RSS Feed | Ajax | Hello-World | J2EE | BPM | EJB | FileNet | Hibernate | ORM | IBM | ILOG | Interview | FAQs |

Java | Apache | JVM | Others | BRMS | Oracle | Pega | SOA | Sun-Certification | Web-Service | websphere | XML |
 

JAVA DEVELOPER SITE - COMPLETE JAVA TUTORIALS

Java Multithreading Example and Source Code Tutorial


Share
 
 

Useful Java Links


       


Multi-threading programming is conceptual paradigm for programming where we divide programs into two or more process which can run in parallel. With interactive network programs, we will find that there are many problems best solved concurrently. Before going see  code examples we will get to  know some thread concepts.

 

Multitasking and MultiThreading

 

In multi-tasking operating system tasks are known as heavy-weight process; in a multithreaded environment tasks are light weight process, or threads. The difference is that heavy weight process are in separate address space and should be thought of as different program running on the same system like Word Excel. Inter-process communication is expensive and limited .Context switching, changing the running process , is also heavy-weight. We usually only think about using one  of these programs at a time, even they are both running. Threads on the other hand share the same address space and co-operatively share the same heavy weight process. Inter-thread communication  is very light-weight and pervasive. Context switching is fast and an integral part of running any one program.

 

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

 

Creating Threads:

 

We can create thread  in a program using class Thread or implementing interface Runnable.

 

Lifecycle of a Thread

Java Threads

  1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
     
  2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
     
  3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

  4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

 

  1. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

A simple program to explain the life cycle of thread

 

class ThreadDemo implements Runnable{

   Thread t;
 ThreadDemo(String s) {
 
 t=new Thread(this,s);
 t.start();//Ready to run
 }
 public void run() {//Running state
for(int i=0;i<5;i++) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
 try{
 
Thread.sleep(1000);//Blocked
}catch(Exception e){}
}
}
//Dead state
}

public class RunnableThreadDemo1{
public static void main(String args[]){
System.out.println("Thread Name :"+Thread.currentThread().getName());
ThreadDemo m1=new ThreadDemo("My Thread 1");//New atate
ThreadDemo m2=new ThreadDemo("My Thread 2");
}
}

 

Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:

                             
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}


}

 

Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:

                             
public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}


}

Messaging

Once our program is divided into several logical threaded parts, we have to define how these threads will communicate with each other. Java provide a clean way for two threads to talk to each other  via the wait() and notify() and notifyall() methods.

 

Thread Priorities

Thread priorities are defined as integers between 1 and 10. Ten is the highest priority. One is the lowest. The normal priority is five. Higher priority threads get more CPU time.

We can set a thread's priority with the setPriority(int priority) method.

 




Download Latest Java/J2EE eBooks, SCJP Dumps, SCWCD Dumps, Pega Tutorial, IBM WebSphere BPM tutorials and many more


If you need any urgent assistance on java-multithreading-tutorial-source-code-examples, kindly email your requirement to us at : info@javagenious.com or Contact-an-Expert. Our experts will try their best to solve your problem.

You can also subscribe to our newsletters on java-multithreading-tutorial-source-code-examples, to receive updates on java-multithreading-tutorial-source-code-examples,via email.Enter you email below:

Enter your email address:

Delivered by FeedBurner



Keyword Tags: java-multithreading-tutorial-source-code-examples tutorial,java-multithreading-tutorial-source-code-examples in java,Concepts of java-multithreading-tutorial-source-code-examples,Java,J2EE,Interview Questions,java-multithreading-tutorial-source-code-examples Examples


Comments:


Post Your Comment:

*

Yes, I would like to recieve email notifications on my reply.

Popular Posts:

 
Popular Downloads

SCJP 1.6 Dumps
JSP Interview Questions
Struts Interview Questions
Hibernate Interview Questions
SCWCD Dumps
SCBCD Dumps

Java/J2EE Tutorial
JMS Tutorials
seam richfaces tutorial
richfaces live demo
jquery example demo
JQuery Tutorial and Source Code
JSF Tutorial
XSL Tutorial
J2EE JMS
CORBA Applications
Java CERTIFICATION
SCJP 1.5
SCJP 1.6
SCWCD 1.5
SCBCD
Mis
Ajax autosuggest autocomplete from database
Struts forms and validation with webflow
Java Apache POI Examples
JDBC Tutorial
Oracle 9i & 10g
MYSQL Tutorial
php Tutorial
JQuery Examples
Upload Java File
JAXB Examples
PL-SQL Tutorial
Dojo AJAX
EJB Examples
Java IDE
Eclipse
NetBeans
IBM Rational Weblogic Workshop
Downloads
SCJP 1.6 Dumps
SCJP 1.5 DUMP
SCJP Material
SCWCD
Java Security
SCBCD Dumps
External Links
SUN Java
JOracle
IBM
PHP Certification
Technical Interview Questions
Amazon Interview Questions
Google Interview Questions
Microsoft Interview Questions
IBM Interview Questions
Yahoo Interview Questions
All Tutorials
php mysql tutorial
SCJP 1.5/1.6
SCWCD 1.5/1.6
Polymorphism
Thread Tutorial
Generics & Exceptions
Spring Struts Hibernate
Java Collections
MAP
SET
LIST
VECTOR
Advanced Java
Stateless Session Bean
Introduction to EJB
Stateful Session Bean
Java Design Patterns
HOME | FORUM | ABOUT | BLOGS | CONTACT-US