可以同时运行两个无限循环吗? [英] Can two infinite loops be ran at once?
本文介绍了可以同时运行两个无限循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够同时运行两个 True
循环.这可能吗?
I want to be able to have two while True
loops running at the same time.
Would this be possible?
我是Python的新手,所以我不知道如何解决这个问题.
I am extremely new to Python, so I do not know how to get round this problem.
这是我编写的代码:
import time
def infiniteLoop():
while True:
print('Loop 1')
time.sleep(1)
infiniteLoop()
while True:
print('Loop 2')
time.sleep(1)
现在,它只打印循环1"
Right now, it just prints a 'Loop 1'
预先感谢
推荐答案
要一次运行两个循环,您要么需要使用两个线程,要么将循环交织在一起.
To run both loops at once, you either need to use two threads or interleave the loops together.
方法1:
import time
def infiniteloop():
while True:
print('Loop 1')
time.sleep(1)
print('Loop 2')
time.sleep(1)
infiniteloop()
方法2:
import threading
import time
def infiniteloop1():
while True:
print('Loop 1')
time.sleep(1)
def infiniteloop2():
while True:
print('Loop 2')
time.sleep(1)
thread1 = threading.Thread(target=infiniteloop1)
thread1.start()
thread2 = threading.Thread(target=infiniteloop2)
thread2.start()
这篇关于可以同时运行两个无限循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文