Unlike many other languages it is simple to create and manage threads in java. Your class can gain the concurrent behavior through either extending java.lang.Thread class or implementing java.lang.Runnable interface. Thread class itself implements Runnable interface, due to the same reason compiler will not force the programmer to give an implementation of run() method if the Thread class is extended.
Today we will give you two sample programs. One class extends java.lang.Thread and another one implements java.lang.Runnable. Both implementations give concurrent behavior for your classes, however the second implementation gives you a chance to extend another class. To start a thread we have to use the start() method in Thread class. Since starting a thread differ from one operating system to another, the start() method is implementation is native. If the run() method is directly called on a Thread object, the run() method will be invoked in the same stack and the code will be executed sequentially. start() method will start a new Thread and the started Thread will run concurrently with the starting Thread.
Thread creation through extending Thread class
1 2 3 4 5 6 7 8 |
class WorkerThread extends Thread{ @Override public void run(){ System.out.println("WorkerThread.run()"); } } |
Thread creation through implementing Runnable interface
1 2 3 4 5 6 7 8 9 |
class WorkerThread1 extends Frame implements Runnable{ private static final long serialVersionUID = 1L; public void run() { System.out.println("WorkerThread1.run()"); } } |
Starting a java Thread
1 2 3 4 5 6 7 8 |
public class ThreadExample { public static void main(String args[]){ Thread thread1 = new WorkerThread(); thread1.start(); Thread thread2 = new Thread(new WorkerThread1()); thread2.start(); } } |