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,
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,
The other way to do this is to implement 'Runnable', as shown below,
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.
- Implementing an interface
- Extending a class
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: Java
import java.lang.*;
public class myExample extends Thread
{
public void run()
{
....
}
}
Code: Java
import java.lang.*;
public class myExample implements Runnable
{
Thread T;
public void run()
{
....
}
}


By the wat welcome to G4EF forum.