Master Python Threading: Create and Manage Threads with Simple Examples
This guide explains Python's Thread class, covering its syntax, common attributes and methods, and provides two practical examples—creating a thread to run a function and subclassing Thread—to help developers understand thread creation, control, and lifecycle management.
Thread class is used to represent an individual control thread.
Syntax
t = Thread(group=None, target=None, name=None, args=(), kwargs={})
Parameters:
group : reserved for future extension, default None.
target : a callable object that the thread will execute when run() is called.
name : thread name, default creates a unique “Thread‑N” name.
args : tuple of arguments passed to the target function.
kwargs : dictionary of keyword arguments passed to the target.
Common Attributes and Methods
t.start(): starts the thread by invoking run(); can be called only once. t.run(): method called when the thread starts; by default calls the target function; can be overridden in a subclass. t.join([timeout]): blocks until the thread terminates or timeout (seconds) occurs. Must be called after start. t.is_alive: returns True if the thread is active, otherwise False. t.name: thread name, can be changed. t.ident: integer thread identifier, None if not started. t.daemon: True if the thread is a daemon (background) thread; the program exits when only daemon threads remain.
Example 1: Using Thread object to create a simple thread and start a function
Code:
#利用Thread对象,简单创建一个线程,并启动一个函数
from threading import Thread
import time
def mark(interval):
print("循环等待时间时间%d,等待前时间:" % (interval, time.ctime()))
time.sleep(interval)
print("等待后的时间:" % time.ctime())
if __name__=="__main__":
t=Thread(target=mark,args=(3,))
t.daemon=False # set as non‑daemon thread to keep main thread alive
t.start()
print("end")Result:
Example 2: Subclassing Thread to implement a thread class
Code:
#通过继承Thread,实现线程类
from threading import Thread
import time
class MyThread(Thread):
def __init__(self, interval):
#下面语句用来调用基类方法,必须调用
Thread.__init__(self)
self.daemon=False
self.interval=interval
def run(self):
print("循环等待时间时间%d,等待前时间:" % (self.interval, time.ctime()))
time.sleep(self.interval)
print("等待后的时间:" % time.ctime())
if __name__=="__main__":
t=MyThread(3)
t.start()
time.sleep(1) # pause to observe output
print("end")Result:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
