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

What is the difference between C++ and Java and your preferences?

855


Difference between static synchronization vs. Instance synchronization?

833


What is finalize()? Is finalize() similar to a destructor?

749


What is bufferedwriter?

748


Why do we use regex?

766


Can a lock be acquired on a class in java programming?

736


What is thread start?

724


What are the types of inner classes (non-static nested class) used in java?

813


When should a function throw an exception?

827


What about interthread communication and how it takes place in java?

806


What are the advantages of java over C++?

934


What is the difference between the reader/writer class hierarchy and the inputstream/outputstream class hierarchy in java programming?

849


What is a vector in java?

791


Does java allow default arguments?

782


Can we overload the constructors?

758