» Java – Thread

A thread in most cases is a component of a process, and shares it’s resources.

In Java – Creating a basic thread and starting it:

(This Example doesn’t provide any code in the start method. So the thread will exit right after it is started).

Thread thread = new Thread();
thread.start();

 

Threads can be provided with codes by two methods:

1. Creating a subclass which extends the superclass of Thread and then override it’s run() method:

public class MySubClassThread extends Thread {
  public void run(){
    System.out.println("MySubClassThread is running");
  }
}
MySubClassThread mySubClassThread = new MySubClassThread ();
MySubClassThread.start();

 

2. Creating an implementation class of the runnable interface:

public class MyImplementationOfRunnable implements Runnable {
  public void run(){
    System.out.println("MyImplementationOfRunnable is running");
  }
}
Thread thread = new Thread(new MyImplementationOfRunnable());
thread.start();

 

Every Thread has a name and you can provide it’s name (else a default name will be chosen automatically):

Thread thread = new Thread("I am a named Thread") {
  public void run(){
    System.out.println("I " + getName() + " ran this code.");
  }
};
thread.start();

You can get the name of the current thread running in any certain block of code:

String threadName = Thread.currentThread().getName();