Python多线程threading的使用

 

一. threading的参数传递,参数之后的’,‘不能少,此处的’,‘是用来区分此参数作为元组(包含多个参数)来传递的,而不是单个参数传递

#coding:utf-8
import threading
import time

def b(arg):
    time.sleep(2)
    print("I'm B")
    print("I'm", threading.current_thread().name)
    print("I'm",arg)
    time.sleep(2)
    print("I'm sleep after")

def a():
    print("I'm A")
    s = threading.Thread(target=b, name='LoopThread',args=("test",))
    s.start()
    print("I'm",threading.current_thread().name)
    #time.sleep(3)
    print("I'm C")

print(a())

二. sleep的位置很重要,如上输出结果:

I'm A
I'm MainThread
I'm C
None
I'm B
I'm LoopThread
I'm test
I'm sleep after

第二种情况:

#coding:utf-8
import threading
import time

def b(arg):
    #time.sleep(2)
    print("I'm B")
    print("I'm", threading.current_thread().name)
    print("I'm",arg)
    time.sleep(2)
    print("I'm sleep after")

def a():
    print("I'm A")
    s = threading.Thread(target=b, name='LoopThread',args=("test",))
    s.start()
    print("I'm",threading.current_thread().name)
    #time.sleep(3)
    print("I'm C")

print(a())

 

输出结果:

I'm A
I'm BI'm
I'm  LoopThread
I'm test
MainThread
I'm C
None
I'm sleep after

第三种情况:

#coding:utf-8
import threading
import time

def b(arg):
    #time.sleep(2)
    print("I'm B")
    print("I'm", threading.current_thread().name)
    print("I'm",arg)
    time.sleep(2)
    print("I'm sleep after")

def a():
    print("I'm A")
    s = threading.Thread(target=b, name='LoopThread',args=("test",))
    s.start()
    print("I'm",threading.current_thread().name)
    time.sleep(3)
    print("I'm C")

print(a())

 

输出结果:

I'm A
I'm BI'm
 MainThread
I'm LoopThread
I'm test
I'm sleep after
I'm C
None

似乎其中一个线程稍微阻塞(或睡眠)就会立马开始执行另外一个,可以据此调控两个线程的交替?

 

关于线程的参数传递需要注意

posted @ 2018-08-14 16:08  sen_c7  阅读(279)  评论(0编辑  收藏  举报