.Thread()
The .Thread()
method is a class constructor that returns a thread object that can run a function with zero or more 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
The object that returns from the .Thread()
constructor can be assigned to its own variable, as shown in the example below:
import threadingthread_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
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.
Codebyte Example 2
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.
Codebyte Example 3
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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.