我想測試它是否可以將追加到來自兩個線程列出,但我發現了凌亂的輸出: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