Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 132,628 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,047 people online right now. Registration is fast and FREE... Join Now!




Java Threads

 
Reply to this topicStart new topic

> Java Threads, An introduction to threads in Java

Rating  2
rahulbatra
Group Icon



post 29 Dec, 2005 - 04:13 AM
Post #1


A thread, by definition is a light weight process. They are used to increase functionality and performance by performing multiple tasks at the same time, i.e. concurrently. There are two methods for implementing threads in Java,
- Implementing an interface
- Extending a class

Now since this is an intermediate level Java programming tutorial, I'd assume that the reader is familiar with the basic Object Oriented Paradigm concepts and understands terms like 'extending', 'interface' and 'class'. Now you may start wondering why are there two ways to create threads. This is because if a class is already an inherited class of some class other than 'Thread', then it cannot extend 'Thread' because multiple inheritance is not allowed in the Java programming language. So, in such cases we use 'Runnable' interface instead.

Now, let's jump onto the coding part on how to actually create threads. The first method is to extend or inherit the 'Thread' class. The 'Thread' class is defined in the package java.lang, which needs to be imported. Take a look at the code below to get a better idea,

CODE

import java.lang.*;

public class myExample extends Thread
{
 public void run()
 {
  ....
 }
}


The other way to do this is to implement 'Runnable', as shown below,

CODE

import java.lang.*;
public class myExample implements Runnable
{
 Thread T;
 public void run()
 {
   ....
 }
}


Notice that both the methods make use of the 'run()' function, which is responsible for the actions of the thread. The 'Runnable' interface actually is nothing but a class containing only one abstract method, 'public abstract void run();'. Remember an interface only provides a design framework upon which classes can be implemented. It is also interesting to note that actually the 'Thread' class also implements the 'Runnable' interface.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/23/08 03:43AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month