Multitasking-

    • – Multitasking = Multi(Many) + Task(Instruction)
    • – Performing multiple tasks at a same time is known as Multitasking.
    • – One Process can execute only 1 instruction at a time.

 

  • MultiThreading-
  • Task = Combination of Program
  • Program = Combination of Process

Single Threaded Application-

  • – Whenever we execute any python program a default thread named as ‘main thread’ will always be execute in backend.

Ex-

class SingleThreadProg:
    def display(self):
        print("Inside display")
        for j in range(1, 3):
            print(j)

    def main():
        obj = SingleThreadProg()
        obj.display()
        print("Inside main")
        for i in range(1, 3):
            print(i)

SingleThreadProg.main()
Output-
Inside display
1
2
Inside main
1
2

MultiThreading Application-

module threading  ---> Thread
clas Thread:
	def run(self):
		pass
	def join(self):
		------
		-----
		
class userThread(Thread)
 def run(self): #override
	----Logical

Life Cycle Of Thread-

Use Of Time Module-

sleep()–> Used to stop the execution for a particular no. of sec.

import time
import threading
class customThread(threading.Thread):
    def main():
        obj = customThread()
        obj.start()
        for i in range(1,6):
            print("i-"+str(i))
            time.sleep(2)
        print("Main thread complete")

    def run(self):
        for j in range(1,6):
            print("j-"+str(j))
            time.sleep(2)
        print("Run thread complete")
customThread.main()

Output-
j-1
i-1
j-2
i-2
j-3
i-3
j-4
i-4
i-5
j-5
Main thread complete
Run thread complete

Ex-

from threading import Thread

class Program1(Thread):
    def run(self):
        print("Program1")

class Program2(Thread):
    def run(self):
        print("Program2")

class MultiThreadProgram:
    def main():
        t1 = Program1()
        t2 = Program2()
        t1.start()
        t2.start()

MultiThreadProgram.main()
Output-
	Program1
	Program2

Join()-

  • – It is a object level method.
  • – It is used to wait for the thread execution until the joined thread execution will not complete.
Menu