Python线程请求计数



当我运行这段代码时,它显示

1     Hello world
2     Hello world
3     Hello world
4     Hello world
5     Hello world
6     Hello world
7     Hello world
8     Hello world
9     Hello world
10     Hello world
1     Hello world
2     Hello world
3     Hello world
4     Hello world
5     Hello world
6     Hello world
7     Hello world
8     Hello world
9     Hello world
10     Hello world
1     Hello world
2     Hello world
3     Hello world
4     Hello world
5     Hello world
6     Hello world
7     Hello world
8     Hello world
9     Hello world
10     Hello world
[Program finished]

如何计数1到20而不是1到10两次

from threading import Thread
def test():
for i in range(10):
print(str(i+1)+"     Hello world")

t1=Thread(target=test)
t2=Thread(target=test)
t1.start()
t2.start()

Thread对象传递一个参数,作为每个线程的偏移量:

def test(offset):
for i in range(10):
print(str(offset + i + 1) + "    Hello world")
t1 = Thread(test, args=(0,))
t2 = Thread(test, args=(10,))
t1.start()
t2.start()

如何计数1到20而不是1到10两次

使用单个线程,范围为20…

>>> def test():
...     for i in range(20):
...         print(str(i+1)+"     Hello world")
...
>>> t1=Thread(target=test)
>>> t1.start()
1     Hello world
2     Hello world
3     Hello world
4     Hello world
5     Hello world
6     Hello world
7     Hello world
8     Hello world
9     Hello world
10     Hello world
11     Hello world
12     Hello world
13     Hello world
14     Hello world
15     Hello world
16     Hello world
17     Hello world
18     Hello world
19     Hello world
20     Hello world

相关内容

  • 没有找到相关文章

最新更新