import time
def countdown(n):
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(5)
# Create and launch a thread
from threading import Thread
t = Thread(target=countdown, args=(10,))
t.start()from threading import Thread
class CountdownTask:
    def __init__(self):
        self._running = True
    def terminate(self):
        self._running = False
    def run(self, n):
        while self._running and n > 0:
            print('T-minus', n)
            n -= 1
            time.sleep(5)
c = CountdownTask()
t = Thread(target=c.run, args=(10,))
t.start()
c.terminate() # Signal termination
t.join()      # Wait for actual termination (if needed)注意使用变量 self._running 退出线程的方式
from threading import Thread
class CountdownThread(Thread):
def __init__(self, n):
    super().__init__()
    self.n = n
def run(self):
    while self.n > 0:
        print('T-minus', self.n)
        self.n -= 1
        time.sleep(5)c = CountdownThread(5) c.start()
import Queue
import threading
import time
task_queue = Queue.Queue()
class ThreadTest(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        while True:
            msg = self.queue.get()
            print(msg)
            time.sleep(0.1)
            self.queue.task_done()
def main():
    start = time.time()
    # populate queue with data
    for i in range(100):
        task_queue.put("message")
    # spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadTest(task_queue)
        t.setDaemon(True)
        t.start()
    # wait on the queue until everything has been processed
    task_queue.join()
    print "Elapsed Time: {}".format(time.time() - start)
if __name__ == "__main__":
    main()setDaemon 设置为 True, run 函数中不需要退出,主线程结束后所有子线程退出 如果 setDaemon 设置为 False,则改为
def run(self):
    while not self.queue.empty():
        msg = self.queue.get()
        print(msg)
        time.sleep(0.1)
        self.queue.task_done()并且在主函数结束前 join 所有线程