class Process extends Thread { int start,end; Process(int s,int e,String name) { start=s; end=e; setName(name); } public void run() { for(int i=start;i<=end;i++) { System.out.println(“thread->”+getName()+” : “+i); try{ Thread.sleep(100); } catch(InterruptedException ex){ex.printStackTrace();} } System.out.println(Thread.currentThread()+ “ : thread Finished....”); } } public class ExtendsThread { public static void main(String[] args) { Process thrd1=new Process(1,5,”Real”); Process thrd2=new Process(6,10,”Java”); thrd1.start(); thrd2.start(); } }
Output: thread->Java : 6 thread->Real : 1 thread->Real : 2 thread->Java : 7 thread->Real : 3 thread->Java : 8 thread->Java : 9 thread->Real : 4 thread->Java : 10 thread->Real : 5 Thread[Java,5,main] : thread Finished.... Thread[Real,5,main] : thread Finished....
public interface Runnable { void run(); }The following program implements Runnable interface for creating threads:
class Job implements Runnable { int start,end; Job(int s,int e) { start=s; end=e; } public void run() { for(int i=start;i<=end;i++) { System.out.println(“thread:”+Thread.currentThread().getName()+”:“+i); try{ Thread.sleep(100); } catch(InterruptedException ex){ex.printStackTrace();} } System.out.println(Thread.currentThread()+ “ : thread Finished....”); } } public class RunnableInterface { public static void main(String[] args) { Job obj1=new Job(1,3); Job obj2=new Job(6,8); Thread thrd1=new Thread(obj1); thrd1.setName(“Real”); Thread thrd2=new Thread(obj2); thrd2.setName(“Java”); thrd1.start(); thrd2.start(); } }