今天在学习多线程编程,由于多个线程是同时启动的,所以输出也出现在了同一行,怎样才能换行输出呢?
输出结果是这样的:
*** MULTIPLE THREADS
startingstartingstarting fibfacsum at:at:at: Tue Dec 08 22:30:43 2015Tue Dec 08 22:30:43 2015Tue Dec 08 22:30:43 2015
facsum finished at:finished at: Tue Dec 08 22:30:44 2015Tue Dec 08 22:30:44 2015
我想要的结果是这样的:
starting fib at: Sat Nov 22 09:51:39 2014
starting fac at:Sat Nov 22 09:51:39 2014
starting sum at:Sat Nov 22 09:51:39 2014
那我应该怎样做呢?
大家讲道理2017-04-17 16:38:38
First of all, thank you for your answers. However, these methods are still not clear to me, a Python beginner.
I solved this problem using other methods.
I thought that the switching between threads is an alternating loop in which one thread executes a few sentences and the other thread executes a few sentences again, and one sentence will not be interrupted.
The original mistake was that I wrote the output statement in this form:
print 'starting', funcs[i].__name__, 'at:',\
ctime()
In fact, in Python’s view, this is not a statement, but the sum of several statements:
print 'starting',
print funcs[i].__name__,
print 'at:',
print ctime()
In this case, the threads will interrupt each other's output, so I changed the output statement and replaced it with this:
print 'starting %s at: %s\n' % (funcs[i].__name__, ctime()),
In this case, the output will be normal.
高洛峰2017-04-17 16:38:38
Each thread puts the content that needs to be output into Queue(), and specifically starts a thread to read data from Queue() and output it to the screen.