I have shared enough theory on Multi-Threading in my previous post. Now, it is time to share code for Multi-Threaded programs by implementing runnable interface.
package MultiThreadingIllustration; class RunnableImplement implements Runnable { Thread t; RunnableImplement() { t = new Thread(this,"Second Thread"); System.out.println("Second Thred Created"); t.start(); } public void run() { try { for(int i=10;i>=0;i--) { System.out.println("Second Therad " +i); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("InterruptedExcpetion Caught"); } System.out.println("Second Thread Exiting"); } } class RunnableDemo { public static void main(String...args) { RunnableImplement ri = new RunnableImplement(); try { for(int i=0;i<=5;i++) { System.out.println("Main Thread " + i); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("Main Thread Interrupted "); } System.out.println("Main Thread Exited"); } }
No comments:
Post a Comment