How to Create Threads in Java - Implement the runnable interface
Threads are used to achieve concurrency meaning running multiple tasks at the same time. One way to use threads in Java is to implement runnable interface and the other is to extend the thread class. In this chapter, We'll learn how to implement runnable interface to implemnet multi-threading in Java.Which of these idioms should you use? The first idiom (implementing the runnable interface), which employs a
Runnable
object, is more general, because the Runnable
object can subclass a class other than Thread
. The second idiom (extending the thread class) is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread
. This lesson focuses on the first approach, which separates the Runnable
task from the Thread
object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs covered later.This program shows how to use Threads in Java by implementing the runnable interface..
ThreadCreationJava.java
public class ThreadCreationJava { public static void main(String args[]){ MyThread thread = new MyThread(); thread.start(); RunnableInterfaceClass runnableInterfaceObject = new RunnableInterfaceClass(); new Thread(runnableInterfaceObject).run(); int iterator = 3; try { for (int i = 0; i < iterator; i++){ System.out.println("From 1st Thread: i = " + i); Thread.sleep(3000); } } catch (InterruptedException e) { System.err.println(e); } } }
MyThread.java
public class MyThread extends Thread { @Override public void run() { int iterator = 5; try { for (int i = 0; i < iterator; i++){ System.out.println("From 2nd Thread: i = " + i); sleep(2000); } } catch (InterruptedException e) { System.err.println(e); } } }
RunnableInterfaceClass.java
public class RunnableInterfaceClass implements Runnable { @Override public void run() { int iterator = 5; try { for (int i = 0; i < iterator; i++){ System.out.println("From 3rd Thread: i = " + i); Thread.sleep(2000); } } catch (InterruptedException e) { System.err.println(e); } } }
No comments:
Post a Comment