Problem : Write a Thread program that execute concurrent execution. Solution : Blow programs has a default thread 'main' that creates two child thread 'Dhoni' and 'Yuvraj' . All these three threads execute a loop that print thread name 500 times on the console. Since all threads are executed concurrently, console output will be very interesting. Due to OS scheduling, output sequence of this program will never be same. Every time you execute program you will get different output sequence. Program :Step 1 - Coding Create a text file c:\sunilos\HelloWithThread.java and copy below contents./* * A program with thread implementation */ // A thread can be made by extending Thread class public class HelloWithThread extends Thread { //instance variable contains Thread name String name = null; //Default constructor, initializes name public HelloWithThread(String threadName) { super(threadName); name = threadName; } //Mandatory run method to perform thread operations public void run() { for (int i = 0; i < 500; i++) { System.out.println(i + " Hello Thread " + name); } } } Step 2 - Creating a test program to test above HelloWithThread classCreate a text file c:\sunilos\TestWithThread.java and copy below contents. /* * A program to test HelloWithThread */ public class TestWithThread { //This method is executed in a default 'Main' thread public static void main(String[] args) { //Main thread created two child thread t1and t2 HelloWithThread t1 = new HelloWithThread("Dhoni"); HelloWithThread t2 = new HelloWithThread("Yuvraj"); //start threads t1.start(); t2.start(); //main thread execute for loop 500 times. Ideally three 'for' loops will be executed from t1, t2 and main threads for (int i = 0; i < 500; i++) { System.out.println(i + " This is Main"); } } } Step 3 - Deployment
Step 4 - Testing
Output0 Hello Thread Yuvraj 0 This is Main 0 Hello Thread Dhoni 1 Hello Thread Yuvraj 1 This is Main 1 Hello Thread Dhoni 2 Hello Thread Yuvraj 2 This is Main 2 Hello Thread Dhoni 3 This is Main 3 Hello Thread Yuvraj 3 Hello Thread Dhoni 4 Hello Thread Yuvraj 4 This is Main 5 Hello Thread Yuvraj 5 This is Main 4 Hello Thread Dhoni ..... <<Previous | Next>> |