Python学习笔记|Python之线程

1.单线程

单线程执行完一件事情才能执行另外一件事件

	def Learn(name,loop):
	    for i in range(loop):
	        print('Learn: %s %s '%(name,time.ctime()))
	        time.sleep(1)
	
	
	def Listen(name, loop):
	    for i in range(loop):
	        print('Listen: %s %s ' % (name, time.ctime()))
	        time.sleep(1)
	
	if __name__ == '__main__':
	    Learn('python', 3)
	    Listen('java',4)
	    print('end time %s'%time.ctime())

2.多线程

  • 创建线程
	threading.Thread(target= Listen,args=('java',4))

  • 启动线程

start()启动线程

  • 守护主线程

设置守护主线程后,如果执行到了主线程,则直接退出

setDaemon(True):
  • 阻塞主线程

join()一直阻塞直到所有子线程结束

join(timeout)阻塞timeout时间

代码如下:

def Learn(name,loop):
for i in range(loop):
    print('Learn: %s %s '%(name,time.ctime()))
    time.sleep(1)


def Listen(name, loop):
    for i in range(loop):
        print('Listen: %s %s ' % (name, time.ctime()))
        time.sleep(1)

  #1.创建线程
t1 = threading.Thread(target= Listen,args=('java',4))
t2 = threading.Thread(target= Learn,args=('python',3))

if __name__ == '__main__':
    #4.守护主线程
    t1.setDaemon(True)
    t2.setDaemon(True)

    #2.启动线程
    t1.start()
    t2.start()

    #3.阻塞主线程,即在所有的子线程结束后再执行主线程
    # t1.join()
    # t2.join()

    print('主线程: %s'%time.ctime())

3.线程锁

  • 创建线程锁
	lock = threading.Lock()
  • 获取线程锁
	lock.acquire()
  • 释放线程锁
	lock.release()

	lock = threading.Lock()  #获取线程锁
	def run_thread(n):
	    for i in range(1000000):
	        #获取锁
	        lock.acquire()
	        try:
	            change(n)
	        finally:
	            #释放锁
	            lock.release()

你可能感兴趣的:(Python)