• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • Getting started with Python
  • Introduction to IDLE
  • Python 2.x vs. Python 3.x
  • Syntax Rules and First Program
  • Numbers and Math Functions
  • Python Operators
  • Python Variables
  • Python Modules and Functions
  • Python Input and Output
  • Data Types in Python
  • String in Python
  • String Functions in python
  • Lists in Python
  • Utilizing List Elements by Iterating
  • Deleting List Elements & other Functions
  • Dictionaries in Python
  • Functions for Dictionary
  • Tuples in Python
  • Relational and Logical Operators
  • Conditional Statements in Python
  • Looping in Python
  • Define Functions in Python
  • Python-Introduction to OOP
  • Object Oriented Programming in Python
  • Classes in Python
  • The concept of Constructor
  • Destructors - Destroying the Object in Python
  • Inheritance in Python
  • Access Modifers in Python
  • Types of Inheritance
  • Method Overriding in Python
  • Polymorphism
  • static Keyword
  • Operator Overloading Python
  • Introduction to Error Handling
  • Exception Handling: try and except
  • Exeption Handling: finally
  • Exception Handling: raise
  • File Handling
  • Reading and Writing File
  • Introduction to Multithreading
  • Threading Module in Python
  • Thread Object
  • Lock Object
  • RLock Object
  • Event Object
  • Timer Object
  • Condition Object
  • Barrier Object
  • __name__ Variable in Python
  • Iterable and Iterator
  • yield Keyword
  • Python Generators
  • Python Closures
  • Python Decorators
  • @property Decorator in Python
  • Assert Statement
  • Garbage Collection
  • Shallow and Deep Copy
  • Introduction to Logging
  • Configure Log LEVEL, Format etc
  • Python Logging in a file
  • Python Logging Variable Data
  • Python Logging Classes and Functions
  • Python MySQL Introduction
  • Create Database - Python MySQL
  • Create Table - Python MySQL
  • Insert Data in Table
  • Select Data from Table
  • Update data in Table
  • Delete data from Table
  • Drop Table from Database
  • WHERE clause - Python MySQL
  • Order By clause - Python MySQL
  • Limit clause - Python MySQL
  • Table Joins - Python MySQL
Home >> python >> Thread Object

Thread Object

Welcome to another tutorial, here we will learn about Thread class and its object in Python. The Thread class is the most commonly used threading module, as it is primarily used to create and run threads. It also, provides all the major functionalities need to create and manage a thread.

The thread objects are the objects of the Thread class in which each object represents an activity to be performed in a separate thread of control in a given program.

We have two ways to create the Thread object and specify the activity to be performed.

  • By passing a callable object to the constructor in a program
  • Or, by overriding the run() method in a given subclass.

Thread object that is created by making use of the constructor or run method can be started by using the start() method. In addition, whenever a Thread object starts a new thread, then internally the method run() is invoked.

Let’s check out the example below:

import time
import threading

def thread1(i):
    time.sleep(3)
    print('No. printed by Thread 1: %d' %i)

def thread2(i):
    print('No. printed by Thread 2: %d' %i)
    
if __name__ == '__main__':
    
    t1 = threading.Thread(target=thread1, args=(10,))
    t2 = threading.Thread(target=thread2, args=(12,))
    # start the threads
    t1.start()
    t2.start()
    # join the main thread
    t1.join()
    t2.join()

Output:

No. printed by Thread 2: 12
No. printed by Thread 1: 10

From the example, we have used the time module to make one of the threads sleep.

Below is the basic syntax of the Thread class constructor:

Thread(group=None, target=None, name=None, args=(), kwargs={})

In the next session, we will discuss how it works.

 

How does Thread works?

If we initialize a thread by making use of the Thread class constructor, so start() method must be called to start the thread.

If the thread starts, the thread is considered alive and active, but if its run() method terminates, either normally, or due to an unhandled exception then the thread stops being alive or active. Therefore, the isAlive() method can be used to test if the thread is alive or not at any given point in time.

Also, the thread's join() method is called to join any thread. It, however, blocks the calling thread until the thread whose join() method was called is terminated.

In the above example, from the main thread, we call t1.join() and t2.join(), therefore the main thread will wait for the threads t1 and t2 to terminate and then end.

All threads have a name associated with them, and that name can be passed to the constructor, or we can set or retrieve the name by using setname() and getname() methods accordingly.

A flag daemon thread could as well be associated with any thread. The importance of this flag is because the entire Python program exits when only daemon threads are left. You can set or retrieve the flag by using setDaemon() method and getDaemon() method respectively.

Note that the main thread object corresponds to the initial thread of control in the python program, and it is not a daemon thread.

 

Functions and Constructor in the Thread class

Let's try to understand the importance of the methods provided by the Thread class along with our code.

 

Thread class Constructor

Below is the basic syntax of the Thread class constructor:

Thread(group=None, target=None, name=None, args=(), kwargs={})

 

The constructor allows many arguments, a few of which are required and some are not. Below is a highlight of what they look like:

  • group: Should be None. It is reserved for future extension.
  • target: This is the callable object or task to be invoked by the run() method. As you can see in the code example at the top, we have specified the function names thread1 and thread2 as the value for this argument. It's default value is None.
  • name: This is used to specify the thread name. By default, a unique name is generated following the format Thread-N, where N is a small decimal number.
  • args: This is the argument tuple for the target invocation. We can provide values in it which can be used in the traget method. It's default value is empty, i.e. ()
  • kwargs: This is keyword argument dictionary for the target invocation. This defaults to {}.

 

start() method

The start() method is used to start the thread's activity. If this method is called, internally the run() method is invoked and executes the target function or the callable object.

 

run() method

It is the Method representing the thread's activity. It can be overridden in a subclass extending the thread class of the threading module. However, the standard run() method invokes the callable object passed to the object's constructor as the target argument with sequential and keyword arguments obtained from the args and kwargs arguments, respectively.

Check out the example.

import threading
import time

class MyThread(threading.Thread):
  # overriding constructor
  def __init__(self, i):
    # calling parent class constructor
    threading.Thread.__init__(self)
    self.x = i
    
  # define your own run method
  def run(self):
    print("Value stored is: ", self.x)
    time.sleep(3)
    print("Exiting thread with value: ", self.x)
    

thread1 = MyThread(1)
thread1.start()
thread2 = MyThread(2)
thread2.start()

Output:

Value stored is:  1
Value stored is:  2
Exiting thread with value:  1
Exiting thread with value:  2

 

join([timeout]) method

If we call this method for any thread, it blocks the calling thread until the thread whose the method join() is called terminates, either normally or through an unhandled exception.

Now, when you want to provide the timeout argument, it should be a floating point number.

 

getName() method

The method is used to return the thread's name.

 

setName(name) method

The method is used for setting the thread's name. The name is a string data type used for only identification purposes.

 

isAlive() method

The isAlive() method returns whether the thread is alive or not. Just like said earlier, a thread is alive from the moment the start() method returns until its method run() terminates.

 

isDaemon() method

The method is typically used to get the value of the thread's daemon flag.

 

setDaemon(daemonic) method

This method is typically used to set the thread's daemon flag to the Boolean value i.e. daemonic. But it must be called before the start() method is called.

In addition, the Python program exists in cases where no active non-daemon thread is left.

 

 

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.