(Translated by https://www.hiragana.jp/)
What does start() function do in multithreading in Java? - GeeksforGeeks
Open In App

What does start() function do in multithreading in Java?

Last Updated : 17 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing Runnable
In both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don’t we directly call the overridden run() function? Why always the start function is called to execute a thread?
What happens when a function is called? 
When a function is called the following operations take place: 
 

  1. The arguments are evaluated.
  2. A new stack frame is pushed into the call stack.
  3. Parameters are initialized.
  4. Method body is executed.
  5. Value is returned and current stack frame is popped from the call stack.

The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM.
Let us see what happens if we don’t call start() and rather call run() directly. We have modified the first program discussed here
 

Java




// Java code to see that all threads are
// pushed on same stack if we use run()
// instead of start().
class ThreadTest extends Thread
{
  public void run()
  {
    try
    {
      // Displaying the thread that is running
      System.out.println ("Thread " +
                Thread.currentThread().getId() +
                " is running");
 
    }
    catch (Exception e)
    {
      // Throwing an exception
      System.out.println ("Exception is caught");
    }
  }
}
 
// Main Class
public class Main
{
  public static void main(String[] args)
  {
    int n = 8;
    for (int i=0; i<n; i++)
    {
      ThreadTest object = new ThreadTest();
 
      // start() is replaced with run() for
      // seeing the purpose of start
      object.run();
    }
  }
}


Output: 
 

Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running

We can see from above output that we get same ids for all threads because we have directly called run(). The program that calls start() prints different ids (see this)

 



Previous Article
Next Article

Similar Reads

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms : Extending the Thread class Implementing the Runnable InterfaceThre
3 min read
Java Thread Priority in Multithreading
As we already know java being completely object-oriented works within a multithreading environment in which thread scheduler assigns the processor to a thread based on the priority of thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creating the thread or it can be gi
5 min read
Deadlock in Java Multithreading
synchronized keyword is used to make the class or method thread-safe which means only one thread can have the lock of the synchronized method and use it, other threads have to wait till the lock releases and anyone of them acquire that lock.  It is important to use if our program is running in a multi-threaded environment where two or more threads
7 min read
Java Multithreading Interview Questions and Answers
Java Multithreading is a fundamental aspect of the Java programming language, enabling developers to create applications that can perform multiple tasks simultaneously, thus improving performance and responsiveness. Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion de
13 min read
MultiThreading in Android with Examples
Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equivalent number of threads are available. For example
3 min read
Java | How to start learning Java
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in
5 min read
Matcher start() method in Java with Examples
The start() method of Matcher Class is used to get the start index of the match result already done. Syntax: public int start() Parameters: This method do not takes any parameter. Return Value: This method returns the index of the first character matched.0 Exception: This method throws IllegalStateException if no match has yet been attempted, or if
2 min read
Matcher start(int) method in Java with Examples
The start(int group) method of Matcher Class is used to get the start index of the match result already done, from the specified group. Syntax: public int start(int group) Parameters: This method takes a parameter group which is the group from which the start index of the matched pattern is required. Return Value: This method returns the index of t
2 min read
Matcher start(String) method in Java with Examples
The start(String string) method of Matcher Class is used to get the start index of the match result already done, from the specified string. Syntax: public int start(String string) Parameters: This method takes a parameter string which is the String from which the start index of the matched pattern is required. Return Value: This method returns the
2 min read
MatchResult start() method in Java with Examples
The start() method of MatchResult Interface is used to get the start index of the match result already done. Syntax: public int start() Parameters: This method do not takes any parameter. Return Value: This method returns the index of the first character matched.0 Exception: This method throws IllegalStateException if no match has yet been attempte
2 min read
MatchResult start(int) method in Java with Examples
The start(int group) method of MatchResult Interface is used to get the start index of the match result already done, from the specified group. Syntax: public int start(int group) Parameters: This method takes a parameter group which is the group from which the start index of the matched pattern is required. Return Value: This method returns the in
2 min read
Difference between Thread.start() and Thread.run() in Java
In Java's multi-threading concept, start() and run() are the two most important methods. Below are some of the differences between the Thread.start() and Thread.run() methods: New Thread creation: When a program calls the start() method, a new thread is created and then the run() method is executed. But if we directly call the run() method then no
3 min read
Best Way To Start Learning Core Java – A Complete Roadmap
In the corporate world, they say "Java is immortal!". It is one of the most robust programming languages that is currently used in more than 3 billion devices. It is a general-purpose, object-oriented programming language designed at Sun Microsystems in 1991. In the current era, Java is one of the most famous programming languages as it can be util
9 min read
Print all Subsequences of String which Start with Vowel and End with Consonant.
Given a string return all possible subsequences which start with a vowel and end with a consonant. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order. Examples: Input : 'abc'Output : ab, ac, abcInput : 'aab'Output : ab, aabQuestion Source: Yatra.com Interview Experi
13 min read
Overriding of Thread class start() method
Whenever we override start() method then our start() method will be executed just like a normal method call and new thread wont be created. We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method, otherwise it ruins multi-threading concept. // Java program illustrate the concept
2 min read
Count ways to reach end from start stone with at most K jumps at each step
Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone. Examples: Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -&gt; s
7 min read
Why Does BufferedReader Throw IOException in Java?
IOException is a type of checked exception which occurs during input/output operation. BufferedReader is used to read data from a file, input stream, database, etc. Below is the simplified steps of how a file is read using a BufferedReader in java. In RAM a buffered reader object is created.Some lines of a file are copied from secondary memory ( or
2 min read
How Does ConcurrentHashMap Achieve Thread-Safety in Java?
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package. Syntax: public class ConcurrentHashMap&lt;K,V&gt; extends AbstractMap&lt;
6 min read
Why does Java's hashCode() in String use 31 as a multiplier?
How hashing is done? A hash works by allocating a value into one of the many storage spaces it has, allowing for fast retrieval later. This storage space is also known as buckets. Hash identifies where to insert which data and that also hash tells in constant time in which bucket the value is stored. Problems with Hash: Now though hashing has the b
3 min read
How does Java process the backspace terminal control character?
What is the backspace terminal control character? In this article, we will discuss about the backspace terminal control character. It is used to move the cursor one character back. For backspace terminal control we use '\b' notation in Java. What does the backspace terminal control character do? By using backspace terminal control we remove the cha
2 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints "Base::show() called".
3 min read
Does Java support goto?
Java does not support goto, it is reserved as a keyword just in case they wanted to add it to a later version. Unlike C/C++, Java does not have goto statement, but java supports label.The only place where a label is useful in Java is right before nested loop statements.We can specify label name with break to break out a specific outer loop.Similarl
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How Does Threading Work in Android?
When an application is launched in Android, it creates the primary thread of execution, referred to as the “main” thread. Most thread is liable for dispatching events to the acceptable interface widgets also as communicating with components from the Android UI toolkit. To keep your application responsive, it's essential to avoid using the most thre
6 min read
What is Apache Kafka and How Does it Work?
When you start with your company it's very simple you have your source system and you have your target system and maybe you need to move data between, for example, your source system is a database and your target system is an analytics system and so you want to move data from A to B and it's very simple. All you need to do is just create an integra
5 min read
Does JVM create object of Main class (the class with main())?
Consider following program. class Main { public static void main(String args[]) { System.out.println(&quot;Hello&quot;); } } Output: Hello Does JVM create an object of class Main? The answer is "No". We have studied that the reason for main() static in Java is to make sure that the main() can be called without any instance. To justify the same, we
1 min read
Java.util.function.BiPredicate interface in Java with Examples
The BiPredicate&lt;T, V&gt; interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on two objects and returns a predicate value based on that condition. It is a functional interface and thus can be used in lambda expression also. public interface BiPredicate&lt;T, V&gt; Methods: test(): This functio
2 min read
Java.util.function.DoublePredicate interface in Java with Examples
The DoublePredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a Double object and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface DoublePredicate Methods test(): This function evaluates a co
2 min read
Java.util.function.LongPredicate interface in Java with Examples
The LongPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on a long value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface LongPredicate Methods test(): This function evaluates a condition
2 min read
Java.util.function.IntPredicate interface in Java with Examples
The IntPredicate interface was introduced in JDK 8. This interface is packaged in java.util.function package. It operates on an integer value and returns a predicate value based on a condition. It is a functional interface and thus can be used in lambda expression also. public interface IntPredicate Methods: test(): This function evaluates a condit
2 min read
Article Tags :
Practice Tags :