The labs on this site need JavaScript to run. The same content is written out below.
Learn › Java › Threads and concurrency
Creating threads and thread states
Why does calling run() directly not create a new thread?
Why it exists — A program with only one flow of execution stops and cannot do other work while it reads a file or waits for a response from another server. Java's Thread puts several flows of execution in one program, so that while one flow waits, another flow does work. A new flow is created only when you call start(), and run() is the method in which you write the task that flow will execute.
Where it's used today — With default settings, Tomcat handles each request with one thread from a thread pool, so even Spring MVC controller code runs on several threads at the same time. In real code, instead of creating new Thread directly, you hand the work to an ExecutorService or to Spring's @Async. You look at thread states when you search for BLOCKED or WAITING threads in the thread dump of a stopped server.
Creating a Thread object and having a thread actually run are two different things. This lab uses t.getState() to follow the states that one thread goes through from the time it is created until it terminates.
Checked against real execution · The 24 combinations were run on JDK 21 and checked against the results
Concepts in this lab
- Processes and threads
- A process is a running program, and the operating system gives it its own independent memory space. A thread is a flow of execution that does the actual work inside a process. The threads of one process share memory (heap, code, and data), and each has only its own stack. This makes it easy for threads to exchange data, but it also causes problems when they touch the same data at the same time.
- Thread states
- These are the six states that a Java thread can be in from the time it is created until it terminates. A thread is in exactly one of them at any moment, and you can check which one with t.getState(). NEW is the state in which only the Thread object has been created and the thread has not started yet, RUNNABLE is the state in which it is running or waiting for its turn to run, and TERMINATED is the state in which it has completed execution. In between, a thread becomes BLOCKED when it waits for a lock that another thread holds, WAITING when it waits with no time limit, and TIMED_WAITING when it waits for a specified time. A thread that has become TERMINATED never returns to another state.
- start() and run()
- Why it exists — The way to create a thread differs for each operating system, so to create one yourself you would have to call that operating system's features. start() leaves this job to the Java virtual machine (JVM), and the work to do is written in run() as an ordinary method, so that the task code and the creation of a thread are separated.
- Where it's used today — In a short example or a test, you start a thread right away with new Thread(task).start(). If you write the work as a Runnable or a lambda, you can also hand the same code to an ExecutorService and run it on a thread of a pool.
- These are two methods of Thread: start() creates a new thread and has that thread execute run(), and run() is an ordinary method that holds the work the thread is to do. So if you call run() directly, no new thread is created, and the calling thread runs that code in order. start() can be called only once on a Thread object, and a second call throws an IllegalThreadStateException. To run the same task again, create a new Thread object.
- join()
- Why it exists — To wait for another thread to finish without join(), you would have to write a loop that keeps asking whether it has finished, write wait/notify signals yourself, or guess the time with sleep. join() lets you move on to the next line as soon as that thread finishes, and it also guarantees that the values the finished thread changed are visible afterward.
- Where it's used today — You use it when you hand work out to several threads and combine the results after all finish, and when you check the result in a test after the threads finish. For tasks handed to a thread pool, you wait with get() of the Future or with CountDownLatch instead of join().
- This method makes the current thread wait until another thread terminates. A thread that calls t.join() does not go on to the next line until t terminates, so it is used when the caller needs to receive and use a result that another thread produces. While it waits, the state of the calling thread is WAITING, and when a time is given, as in join(1000), it is TIMED_WAITING. When it is called on a thread that has already terminated or has not started yet, it returns right away without waiting.
- Interrupt
- Why it exists — Thread.stop(), which stops a thread directly from outside, cuts off what it is doing anywhere and can leave half-modified data, so it stopped being used. Interrupt is what is used instead, and it lets the thread finish or undo the data it was modifying and then end by itself.
- Where it's used today — shutdownNow() of ExecutorService and cancel(true) of Future usually send an interrupt to a running task to request cancellation. A long-running loop checks the interrupt mark with isInterrupted() and responds to this request.
- This is a signal sent to a waiting thread to tell it to stop waiting. When t.interrupt() is called, the interrupt status of t, the mark that says "this thread was interrupted", is set, and if t was waiting in sleep, join, or wait, that method throws an InterruptedException and the thread wakes up right away. It is not a feature that forces a thread to stop, so what to do after receiving the signal is decided by the code of that thread. A thread in the BLOCKED state, waiting for the lock of synchronized, is not woken up by an interrupt.
Try these
- Default settings — run() is called directly. The task runs, but the thread that runs it is main, and t stays NEW to the end.
- Starting with start() — A new thread, worker, runs the task, and t is TIMED_WAITING while worker sleeps.
- A thread that waits with join — A thread that waits, with no time limit, for another thread to terminate is WAITING.
- A thread that waits for a lock — A thread that is blocked at a lock held by another thread is BLOCKED.
- Interrupting a sleeping thread — sleep throws an InterruptedException, and the thread wakes up right away.
- Interrupting a thread that waits for a lock — The thread does not wake up. Only its interrupt status is set.
- Calling start() again on a terminated thread — An IllegalThreadStateException is thrown.
Running with the default settings
- new Thread(task, "worker"): This creates the Thread object t. So far only the object exists, and no new flow of execution (thread) has started. That is why t.getState() is NEW.
- t.run(): run() is an ordinary method call. No new thread is created, and the main thread runs the code of the task directly. The state of t stays NEW.
- Thread.currentThread().getName(): The name of the thread that runs the first line of the task is main. No thread named worker has ever come into being.
- Thread.sleep(1000): The main thread itself sleeps for 1 second. During that time main stays inside t.run() and cannot go on to the next line. After 1 second the task ends and t.run() returns.
- t.getState() after Thread.sleep(100): start() has never been called on t, so t is still NEW. The task ran, but it was not the thread t that ran it.
- t.join(): With a thread that was never started, there is nothing to wait for, so join() returns right away.
- t.getState(): The state is NEW to the very end. The task ran, but t was never started.
Result of this run
- Calling run() directly does not add a thread. The calling thread simply runs that code in order, so nothing runs concurrently. To run the code in a new thread, call start(). start() creates a new thread, and that thread runs run().
Code
// Only the lines inside main are shown (class, main declaration, and imports omitted)
Runnable task = () -> {
System.out.println(Thread.currentThread().getName()); // the name of the thread that runs this line
try {
Thread.sleep(1000); // sleeps for 1 second
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
};
Thread t = new Thread(task, "worker");
System.out.println(t.getState());
t.run(); // calls the method directly
Thread.sleep(100); // waits briefly so that the task can make progress
System.out.println(t.getState());
t.join(); // waits until t terminates
System.out.println(t.getState());
Assumptions of this model
The results of the 24 combinations (the name of the thread that ran the task, t.getState() partway and at the end, the exceptions thrown, and the interrupt status when the task ends) were checked against the results of running them on JDK 21 in our test environment. In the code on the screen, main waits briefly with Thread.sleep(100) and then looks at the state, but these 100 milliseconds are only a time that is "usually enough", not a guaranteed one. So that the check would not depend on timing, the state of t was checked repeatedly until it had left RUNNABLE and stayed where it was. If t.getState() is called right after start(), the state can be RUNNABLE or already another state, so that value was not used as a result. RUNNABLE does not distinguish "running" from "waiting for a turn on the CPU", and Java does not report the two separately. WAITING also results from Object.wait() or LockSupport.park() besides join, but this lab covers only join. The problems of data that several threads share are covered in the "Race condition" lab, and how to create threads in advance and reuse them is covered in the "Thread pool" lab.
Previous lab: Processes and threads · Next lab: Race condition