我想测试它是否可以将追加到来自两个线程列出,但我发现了凌乱的输出:Python的多线程列表追加
import threading
class myThread(threading.Thread):
def __init__(self, name, alist):
threading.Thread.__init__(self)
self.alist = alist
def run(self):
print "Starting " + self.name
append_to_list(self.alist, 2)
print "Exiting " + self.name
print self.alist
def append_to_list(alist, counter):
while counter:
alist.append(alist[-1]+1)
counter -= 1
alist = [1, 2]
# Create new threads
thread1 = myThread("Thread-1", alist)
thread2 = myThread("Thread-2", alist)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
print alist
所以输出:
Starting Thread-1
Exiting Thread-1
Starting Thread-2
Exiting Main Thread
Exiting Thread-2
[1[1, 2[, 1, 2, 23, , 34, 5, 6, ]4
, 5, , 3, 64, 5, ]6]
为什么它太乱了,alist不等于[1,2,3,4,5,6]?
如果从run()方法中删除print self.alist,它会起作用吗? – snakecharmerb
不,它仍然凌乱不等于[1,2,3,4,5,6] – Alexey