.Thread()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 3, 2022Updated Apr 22, 2025
Contribute to Docs

The .Thread() constructor from Python’s threading module creates a thread object that can run a specified function with optional arguments.

Syntax

threading.Thread(target=callable, args=())

Functions are commonly passed as the target argument, but without parentheses. If any items are listed in the args tuple, they are passed as positional arguments to the target.

Example: Basic Thread Creation

The object that returns from the .Thread() constructor can be assigned to its own variable, as shown in the example below:

import threading
thread_1 = threading.Thread()
thread_2 = threading.Thread()
print(thread_1)
print(thread_2)

Every thread object has a name attribute that, unless otherwise specified, defaults to Thread-x:

<Thread(Thread-1, initial)>
<Thread(Thread-2, initial)>

Codebyte Example 1: Simple Greeting Thread

In the example below, a thread, hello_thread, targets the say_hello() function with supplied arguments. After the thread is created, the targeted say_hello() function is executed when the .start() method is run:

Code
Output
Loading...

Codebyte Example 2: Concurrent File Downloads

In the example below, two threads, thread_1 and thread_2, target the download_file() function with supplied arguments. Each thread simulates downloading a file concurrently by running the download_file() function in the background. After the threads are created, the targeted download_file() functions are executed when the .start() method is run:

Code
Output
Loading...

Codebyte Example 3: Parallel Task Execution

In the example below, two threads, coffee_thread and toast_thread, target the make_coffee() and toast_bread() functions, respectively. Each thread simulates the preparation of coffee and toast concurrently. After the threads are created, the targeted functions are executed when the .start() method is run:

Code
Output
Loading...

Frequently Asked Questions

1. How to sleep a thread in Python?

To sleep a thread in Python, use the time.sleep() function. Import the time module and call time.sleep(seconds) where seconds is the number of seconds to pause the thread. This is useful for adding delays, simulating wait times, or creating periodic tasks in Python’s threading.

2. Is Pandas single-threaded?

Pandas is primarily single-threaded by default. However, some functions (like read_csv() with engine='pyarrow') can use multi-threading or multi-processing for performance.

3. Is Node.js single-threaded?

Node.js operates on a single-threaded event loop model but handles concurrent operations through asynchronous callbacks. For true parallelism in Node.js, you can use the Worker Threads API or the cluster module.

All contributors

Contribute to Docs

Learn Python on Codecademy