python threading

时间:2022-06-20 03:14:43

//test.py

1 import threading

2 import time

3

4 exitFlag = 0

5

6 class myThread (threading.Thread):

7     def __init__(self, threadID, name, counter):

8         threading.Thread.__init__(self)

9         self.threadID = threadID

10         self.name = name

11         self.counter = counter

12     def run(self):

13         print "Starting " + self.name

14         print_time(self.name, self.counter, 5)

15         print "Exiting " + self.name

16

17 def print_time(threadName, delay, counter):

18     while counter:

19         if exitFlag:

20                 #threading.Thread.exit()

21                 return

22         time.sleep(delay)

23         print "%s: %s" % (threadName, time.ctime(time.time()))

24         counter -= 1

25

26 thread1 = myThread(1, "Thread-1", 1)

27 thread2 = myThread(2, "Thread-2", 2)

28

29 thread1.start()

30 thread2.start()

31

32 #exitFlag = 1

33

34 print "Exiting Main Thread"

//result

# python test.py
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Wed Nov 15 01:25:59 2017
Thread-2: Wed Nov 15 01:26:00 2017
Thread-1: Wed Nov 15 01:26:00 2017
Thread-1: Wed Nov 15 01:26:01 2017
Thread-2: Wed Nov 15 01:26:02 2017
Thread-1: Wed Nov 15 01:26:02 2017
Thread-1: Wed Nov 15 01:26:03 2017
Exiting Thread-1
Thread-2: Wed Nov 15 01:26:04 2017
Thread-2: Wed Nov 15 01:26:06 2017
Thread-2: Wed Nov 15 01:26:08 2017
Exiting Thread-2