Previous | Home | Next |
Runnable interface contains only one method. that is:
public void run();
This method implemented by the class inherits Runnable interface. Use of Runnable interface is as follows.
Example
/* * Save as use_runnable.java * Using Runnable interface */ package multithradingexample2; class threaddemo implements Runnable{ Thread t; threaddemo(String name) { t=new Thread(this,"Demo Thread"); t.setName(name); t.start(); } public void run() { for(int i=0;i<3;i++) { try{ System.out.println(t.getName()); Thread.sleep(500); } catch(InterruptedException e) { System.out.println(e.toString()); } } } } public class use_runnable { public static void main(String[] str) { threaddemo th1=new threaddemo("first thread"); threaddemo th2=new threaddemo("second thread"); } }
Output:
first thread second thread second thread first thread second thread first thread
In above program an instance of Thread class created in constructor of thread demo class. This instance calls start() method. Without calling start() Thread can't be initiated.
Sleep method used in above program. suspend that thread for few time period. It is static method , hence called by class name . Argument passed in sleep method is time in milliseconds.
-
public string getName():Get name of thread
-
public void setName(String ):Set name of thread
-
public boolean isAlive():Check whether thread is alive or not.
-
public void join() or pubic void join(int millisecond):suspend the thread
-
public void setPriority(int):Set priority of the tthread
-
pulic int getPriority():obtain priority of a thread.
Previous | Home | Next |