python 多线程

启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行

#coding=utf-8
import time, threading
# 新线程执行的代码:
def loop():
    print 'thread %s is running...' % threading.current_thread().name
    n = 0
    while n < 5:
        n = n + 1
        print 'thread %s >>> %s' % (threading.current_thread().name, n)
        time.sleep(1)
    print 'thread %s ended.' % threading.current_thread().name

print 'thread %s is running...' % threading.current_thread().name
threads = []
t1 = threading.Thread(target=loop,name='xxyy11')
threads.append(t1)
t2 = threading.Thread(target=loop,name='xxyy22')
threads.append(t2)
for t in threads:
    t.start()
    t.join()
print 'thread %s ended.' % threading.current_thread().name



C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/thread/p5.py
thread MainThread is running...
thread xxyy11 is running...
thread xxyy11 >>> 1
thread xxyy11 >>> 2
thread xxyy11 >>> 3
thread xxyy11 >>> 4
thread xxyy11 >>> 5
thread xxyy11 ended.
thread xxyy22 is running...
thread xxyy22 >>> 1
thread xxyy22 >>> 2
thread xxyy22 >>> 3
thread xxyy22 >>> 4
thread xxyy22 >>> 5
thread xxyy22 ended.
thread MainThread ended.

Process finished with exit code 0


这个看起来像串行的



#coding=utf-8
import time, threading
# 新线程执行的代码:
def loop1():
    print 'thread %s is running...' % threading.current_thread().name
    n = 0
    while n < 10:
        n = n + 1
        print 'thread %s >>> %s' % (threading.current_thread().name, n)
        time.sleep(1)
    print 'thread %s ended.' % threading.current_thread().name

def loop2():
    print 'thread %s is running...' % threading.current_thread().name
    n = 10
    while n < 20:
        n = n + 1
        print 'thread %s >>> %s' % (threading.current_thread().name, n)
        time.sleep(1)
    print 'thread %s ended.' % threading.current_thread().name

print 'thread %s is running...' % threading.current_thread().name
threads = []
t1 = threading.Thread(target=loop1,name='xxyy11')
threads.append(t1)
t2 = threading.Thread(target=loop2,name='xxyy22')
threads.append(t2)
for t in threads:
    t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name

C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/thread/p5.py
thread MainThread is running...
thread xxyy11 is running...
thread xxyy11 >>> 1
thread xxyy22 is running...
thread xxyy22 >>> 11
thread xxyy22 >>> 12thread xxyy11 >>> 2

thread xxyy11 >>> 3
thread xxyy22 >>> 13
thread xxyy11 >>> 4
thread xxyy22 >>> 14
thread xxyy11 >>> 5
thread xxyy22 >>> 15
thread xxyy11 >>> 6
thread xxyy22 >>> 16
thread xxyy11 >>> 7
thread xxyy22 >>> 17
thread xxyy11 >>> 8
thread xxyy22 >>> 18
thread xxyy11 >>> 9
thread xxyy22 >>> 19
thread xxyy11 >>> 10
thread xxyy22 >>> 20
thread xxyy11 ended.
thread xxyy22 ended.
thread MainThread ended.

Process finished with exit code 0

这个就变成并行的


原文地址:https://www.cnblogs.com/hzcya1995/p/13349552.html