java thread question.
Could you please give me a multiple thread program example that all threads run in parallel?
Multithreading is a feature of OOPs which provides tasks to be executed concurrently at an intsance using each individual threads created.
Below is an example -
public class Main implements Runnable
{
public static void main(String[] args) {
Thread t1 = new Thread("Thread number-1");
Thread t2 = new Thread("Thread number-2");
t1.start();
t2.start();
System.out.println("Thread names are following:");
System.out.println(t1.getName());
System.out.println(t2.getName());
}
@Override
public void run() {
}
}
Exaplantion :
-- The class which contains main method should implements runnable interface as the instances of the that particular class needs to executed using threads)
-- t1 and t2 are two thread instances created to perform two different tasks simultaneously. The name of t1 instance is 'Thread number -1' and t2 instance is 'Thread number -2'
--start() is a method internally calls the run() method which is defined under runnable interface. This method used to start the execution of the that particular thread instance through which it is called. In simpler words, calling start() method means instructing compiler to execute the definition defined in run() method.
--getName() method is used to get the name of thread instantiated.
--run() contains the task related code. Here the code sequence doesn't matter after the thread starts, rather each thread starts doing their individual task mentioned in run() method.
Get Answers For Free
Most questions answered within 1 hours.