How to Create Threads in Java - Extending the Thread Class
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. We'll learn how to extend the thread class to implement 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
. 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 extending the thread class..
ThreadCreationJava.java
public class ThreadCreationJava { public static void main(String args[]){ MyThread thread = new MyThread(); thread.start(); 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); } } }
No comments:
Post a Comment