multithreading, java program to multithreading
Write a java program to multithreading concept.

Program Algorithm:
Step 1: Create a class which either extends Thread or implements Runnable.
Step 2: This class itself makes its own object to the thread and calls the start method which will call the run method.
Step 3: Define the run method.
Step 4: Create an object of this class in main and the thread will start automatically as the start is called in its constructor.
Step 5: So we have 2 threads: one which you have made and the other is the main thread running simultaneously.

Program Code:
class ThreadDemo 
{
public static void main(String args[])
{ new NewThread();
try
{
for(int i = 5; i > 0; i--)
System.out.println("Main Thread: " + i);
Thread.sleep(1000); 
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
System.out.println("Main thread exiting.");
}
}
class NewThread implements Runnable 
Thread t;
NewThread() 
{
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
public void run() 
{
try 
{
for(int i = 5; i > 0; i--)
System.out.println("Child Thread: " + i);
Thread.sleep(500); 
}
}
catch (InterruptedException e)
System.out.println("Child interrupted."); 
}
System.out.println("Exiting child thread."); 
}
}

Sample Inputs and Outputs:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
CS1031/OOPS Lab CSE/SRM 55/57
Child Thread: 2
Child Thread: 1
Main Thread: 3
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: