Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Friday, 25 November 2016

Creating Multiple Threads In Java

Previously we have discussed about

Till now we have been using only two threads: the main thread and one child thread.
We can use as many threads as we want, But now we are using three threads in below example.

Example of Creating Multiple Threads:

class NewThread implements Runnable{

String name;
Thread t;
public NewThread(String threadName) {
name = threadName;
t = new Thread(this,name);
}
@Override
public void run() {
try {
for(int i=0;i<5;i++){
System.out.println(name+" : "+i);
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(name +" Exit.");
}
}
public class Test {

public static void main(String[] args) {
NewThread t = new NewThread("One");
NewThread t1 = new NewThread("Two");
NewThread t2 = new NewThread("Three");
t.run();
t1.run();
t2.run();
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Main thread exiting.");
}
}
Program Output:

One : 0
One : 1
One : 2
One : 3
One : 4
One Exit.
Two : 0
Two : 1
Two : 2
Two : 3
Two : 4
Two Exit.
Three : 0
Three : 1
Three : 2
Three : 3
Three : 4
Three Exit.
Main thread exiting.
      

Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment