Python 多线程操作操作,线程2不执行

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
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值