www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons Java Threads Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Java supports concurrency through threads which are lightweight processes. A thread is similar to a real process in that a thread and a running program are threads of execution. A thread takes advantage of the resources allocated for that program instead of having to allocate those resources again. A thread has its own stack and program counter. The code running within the thread works only within the context implied by the stack and PC, also called an execution context.

Creating Java Threads

There are two ways to create our own Thread object:
  1. Subclassing the Thread class and instantiating a new object of that class
  2. Implementing the Runnable interface
In both cases the run() method should be implemented. This is elaborated with the help of following examples:

Example of Extending Thread
public class ThreadExample extends Thread {
   public void run () {
      for (int i = 1; i <= 100; i++) {
         System.out.println(“Thread: ” + i);
	  }
   }
}
Example of Implementing Runnable
public class RunnableExample implements Runnable {
   public void run () {
      for (int i = 1; i <= 100; i++) {
         System.out.println (“Runnable: ” + i);
      }
   }
}
It may be noted that both of these are very similar to each other with minor syntactic and semantic differences.

Starting the Threads
A thread is started by simply sending the start message to the thread. This is shown in the following example:
public class ThreadsStartExample {
   public static void main (String argv[]) {
      new ThreadExample ().start ();
      new Thread(new RunnableExample ()).start ();
   }
}

Next >>> Lesson No. 22: Java Threads 2







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.