python-day38(正式学习)

线程

线程开启的两种方式

1

from threading import Thread
import time

def test():
    print('hello world')

t=Thread(target=test)
t.start()
print('hello')
time.sleep(1)
print('world')

2

from threading import Thread
import time

class mythread(Thread):
    def run(self):
        print('hello world')
        time.sleep(1)
        print('hhh')

m=mythread()
m.start()
print('ok')

子线程和子进程的创建速度

from threading import Thread
from multiprocessing import Process
import time

def test(name):
    print('hello world',name)
    time.sleep(1)
    print('ok',name)


if __name__ == '__main__':
    p=Process(target=test,args=('子进程',))
    t=Thread(target=test,args=('子线程',))
    print('zhu')
    p.start()
    t.start()
    print('zhu1')

子线程共享资源

from threading import Thread
import os,time

x=100
def test():
    global x
    x=50
    print('hello ',x)
    print(os.getpid())

t=Thread(target=test)
t.start()
print('zhu ',x)
print(os.getpid())

线程的join方法

from multiprocessing import Process
from threading import Thread
import time
def task():
    print('进程 开启')
    time.sleep(10)
    print('进程 结束')
def task2():
    print('子线程 开启')
    time.sleep(2)
    print('子线程 结束')

if __name__ == '__main__':
    p = Process(target=task)
    t = Thread(target=task2)
    t.start() # 开线程
    p.start() # 开进程
    print('子进程join开始')
    p.join() # 主进程的主线程等待子进程运行结束
    print('主')

守护线程

from threading import Thread
import time
def shouhu():
    print('我是守护xian程')
    time.sleep(10)
    print('shouhu end')

t=Thread(target=shouhu)
t.daemon=True
t.start()
print('nice')

线程其他用法

from threading import Thread,currentThread,enumerate,activeCount
# import threading
import time
# threading.current_thread()
# threading.current_thread()

def task():
    print('子线程 start')
    time.sleep(2)
    print('子线程 end')
    print(enumerate())
    # print(currentThread(),'子线程')
if __name__ == '__main__':
   t1 = Thread(target=task)
   t2 = Thread(target=task)
   t1.start()
   t2.start()



   print(t1.is_alive()) # True
   print(t1.getName()) # Thread-1
   print(t2.getName()) # Thread-2
   t1.setName('班长')
   print(t1.getName())
   print(currentThread().name)
   print(enumerate()) # [<_MainThread(MainThread, started 1856)>, <Thread(Thread-1, started 6948)>, <Thread(Thread-2, started 3128)>]
   print(activeCount()) # 3
   print(len(enumerate())) # 3
posted @ 2019-09-17 16:13  wind叶  阅读(180)  评论(0编辑  收藏  举报