Multithreading in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

#Program for Multithreading
import time
from threading import *
# def printtable(n):
#     for i in range(1,11,1):
#         print(n*i)
#         time.sleep(1)

# def square(limit):
#     for i in range(1,limit+1,1):
#         print(i*i)
#         time.sleep(1)

# #Main calling
# start=time.time()
# printtable(5)
# square(10)
# end=time.time()
# print(end-start)
# --------------------------------------------------------------------------

def display(n):
    for i in range(1,n+1):
        print(i)
        time.sleep(1)

def show(n):
    for i in range(100,n+1):
        print(i)
        time.sleep(1)


#Main Thread(Calling place)

#start=time.time()
# T1=Thread(target=display,args=(20,),name="FirstThread")
# T2=Thread(target=show,args=(120,),name="SecondThread")
T1=Thread(target=display,args=(10,))
T2=Thread(target=show,args=(110,))

# print(T1.getName())
# print(T2.getName())

# T1.setName("First")
# T2.setName("Second")

# print(T1.getName())
# print(T2.getName())

T1.start()
T2.start()

print(T1.is_alive())
print(T2.is_alive())

T1.join()
T2.join()

print(T1.is_alive())
print(T2.is_alive())

# end=time.time()

# print(end-start)

Program 2

import time
from threading import *

class MyThread1(Thread):
    def run(self):
        for i in range(1,11):
            print(i)
            time.sleep(1)

class MyThread2(Thread):
    def run(self):
        for i in range(100,111):
            print(i)
            time.sleep(1)


#Main Thread
M1=MyThread1()
M2=MyThread2()

M1.start()
M2.start()

print(M1.is_alive())
print(M2.is_alive())

M1.join()
M2.join()

print(M1.is_alive())
print(M2.is_alive())

# print(M1.getName())
# print(M2.getName())

# print(current_thread().getName())
# current_thread().setName("Hello Thread")
# print(current_thread().getName())

Program 3

import time
from threading import *

class MyThread1(Thread):
    def run(self):
        for i in range(1,11):
            print(i)
            time.sleep(1)

M1=MyThread1()
M2=MyThread1()
print(M1.getName())
print(M2.getName())

M1.start()
M2.start()

 

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *