Python 多线程操作操作,线程2不执行
问题:在多线程操作过程中,线程1中的有死循环,在执行的过程中,线程2一直不执行。
Code before update
import threading
import time
class test():
def print_111(self):
while 1:
print('111')
time.sleep(1)
def print_222(self):
while 1:
print('222')
time.sleep(1)
if __name__=='__main__':
t = test()
threading.Thread(target=t.print_111()).start()
threading.Thread(target=t.print_222()).start()
Result
111
111
111
111
111
111
111
解决方案:
把传递的函数后面的()去掉,在执行过程的时候,线程2就可以正常执行,加上()之后线程1执行结束之后才开始执行线程2(多线程的效果没有体现出来)。
Code after update
import threading
import time
class test():
def print_111(self):
while 1:
print('1111')
time.sleep(1)
def print_222(self):
while 1:
print('222')
time.sleep(1)
if __name__=='__main__':
t = test()
threading.Thread(target=t.print_111).start()
threading.Thread(target=t.print_222).start()
Result
1111
222
1111
222
222
1111
222
1111
222
1111
222
1111