开发者

how to print this number in a shortest time using thread in python

this is my code :

import thread

k=0
b=0
def a(n):
    i = 0
    while i<n:
        print i
        i += 1

j = 5000

while k < 5000:
    a(k)
    k+=1
for n in rang开发者_JAVA百科e(2,5):
    thread.start_new_thread(a,(j*n,))

and i want to Run three threads and a main thread,

the main thread print 1,2,3,4,5,....5000
and the thread1 print 5001,5002,5003,...10000
the thread2 print 10001,10002,10003,...15000
the thread3 print 15001,15002,15003,...20000

they are at the same time

so what can i do ,

thanks


You should use threading instead of thread, since it's easier to implement and it works in almost every case. Now your code will be like:

import threading 

class PrintNumber(Thread):
  def __init__(self, n):
    self.n = n

  def run(self):
    for i in range(n, n+5000):
      print i

# create your threads here
# use a cicle if needed
thread = PrintNumber(0) # first 5000 numbers
thread.start()
thread = PrintNumber(5000) # next 5000
thread.start()

Coded from mind and have not tested it, should be working anyway

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜