How to create two different thread class inside a main function?

Answer Posted / lakshmi

The main important property of threads for concurrent and
parallel programming is the possibility for a thread to
execute in parallel with the application's main thread or
with other threads. When the start() method is invoked a
new thread is run, but the process which called the start()
method will continue executing its own thread. Par
consequence, the process can call once again the start()
method and run another thread and so on, creating and
running different threads in parallel. For example,
consider the following program,

class Thready {
public static void main( String args [] ) {
new MyThread("A").start();
new MyThread("B").start();
}
}

class MyThread extends Thread {
String message;

MyThread ( String message ) {
this.message = message;
}

public void run() {
while ( true )
System.out.print( message );
}
}
In this program, the lines


new MyThread("A").start();
new MyThread("B").start();

of the main(String args []) function of the class Thready
start two threads of the class MyThread which are run in
parallel. The thread which is initialized with the message
"A" is started first and the thread which is initialized
with the message "B" is stared immediately after the first
thread was started. But the threads will execute in
parallel since they are infinite loops. Otherwise the first
thread which only prints a message can terminate before the
second thread is started and the parallelism of the two
threads can not occur.

Is This Answer Correct ?    5 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain try and catch keywords in java?

623


Is hashset ordered java?

590


Make a data structure and implement an algorithm to print all the files in a directory. (The root directory can have sub-directories too.)

857


Which is bigger float or double?

518


Can we declare the static variables and methods in an abstract class?

548






What is port number in java?

591


How do you create a sop?

529


Give differences between Quicksort & Mergesort. When should these sorts be used and what is their running time?

572


What is the default value of local and global variables?

567


What is return used for in java?

522


What is the impact of declaring a method as final?

562


Give a brief description of java socket programming?

527


What does n mean in java?

504


What is better- service oriented or batch oriented solutions?

1537


How do you achieve singleton?

533