1)Extend the java.lang.Thread class.
2)Override the run() method.
class MyThread extends Thread {
public void run() {
System.out.println("Important job running in MyThread");
}
}
Threads can be created by extending Thread and overriding the public void run() method.
class NameRunnable implements Runnable {
public void run() {
for (int x = 1; x < 4; x++) {
System.out.println("Run by "
+ Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { }
}
}
}
public class ManyNames {
public static void main (String [] args) {
// Make one Runnable
NameRunnable nr = new NameRunnable();
Thread one = new Thread(nr);
one.setName("Fred");
Thread two = new Thread(nr);
two.setName("Lucy");
Thread three = new Thread(nr);
three.setName("Ricky");
one.start();
two.start();
three.start();
}
}
When a Thread object is created, it does not become a thread of execution until its start() method is invoked.
When a Thread object exists but hasn't been started, it is in the new state and is not considered alive.
If start() is called more than once on a Thread object, it will throw a RuntimeException.
Once a new thread is started, it will always enter the runnable state.
The thread scheduler can move a thread back and forth between the runnable state and the running state.
There is no guarantee that the order in which threads were started determines the order in which they'll run.
There's no guarantee that threads will take turns in any fair way.
When the sleep or wait is over, or an object's lock becomes available, the thread can only reenter the runnable state(from waiting to running).
A dead thread cannot be started again.