4
from threading import Thread
import time
class ThreadTest():

    def loop1(self):
        for i in range(0, 100, 5):
            print(i)
            time.sleep(2)

    def loop2(self):
        for i in range(100, 210, 11):
            print(i)
            time.sleep(2)

if __name__ == '__main__':
    T1 = Thread(target=ThreadTest().loop1(), args=())
    T2 = Thread(target=ThreadTest().loop2(), args=())
    T1.start()
    T2.start()
    T1.join()
    T2.join()

The above code runs the methods in sequence rather than simultaneously. I want a way where I can run two method/process simultaneously.

BlackCoffee
  • 171
  • 3
  • 10

1 Answers1

6

Simple bug in your code.

Replace:

T1 = Thread(target=ThreadTest().loop1(), args=())
T2 = Thread(target=ThreadTest().loop2(), args=())

With:

T1 = Thread(target=ThreadTest().loop1, args=())
T2 = Thread(target=ThreadTest().loop2, args=())

Because you're calling the functions loop1() and loop2() in the main thread, they're going to run sequentially. You want to point to the functions, without actually calling them so the subthreads can call them themselves.

SCB
  • 5,821
  • 1
  • 34
  • 43