我在下面的(半)工作示例中有4個工作線程。我只能讓前三個工作線程工作。我怎樣才能讓第四個線程運行?使用moveToThread在PyQt5中啓動QThreads。一個線程無法正常啓動
print(QThread.idealThreadCount())
在我的筆記本電腦上返回'8'。
我可以對代碼進行重新排序以使3個工作人員的任意組合運行。
from PyQt5.QtCore import QThread, QObject
from PyQt5.QtWidgets import QWidget
import sys
from PyQt5.QtWidgets import QApplication
import time
class A(QObject):
def run(self):
while 1:
print('A', time.ctime())
time.sleep(1)
class B(QObject):
def run(self):
while 1:
print('B', time.ctime())
time.sleep(1)
class C(QObject):
def run(self):
while 1:
print('C', time.ctime())
time.sleep(1)
class D(QObject):
def run(self):
while 1:
print('D', time.ctime())
time.sleep(1)
class window1(QWidget):
def __init__ (self, parent = None):
super().__init__() #parent widget
print(QThread.idealThreadCount())
self.thread1 = QThread()
obj1 = A()
obj1.moveToThread(self.thread1)
self.thread1.started.connect(obj1.run)
self.thread1.start()
self.thread2 = QThread()
obj2 = B()
obj2.moveToThread(self.thread2)
self.thread2.started.connect(obj2.run)
self.thread2.start()
self.thread3 = QThread()
obj3 = C()
obj3.moveToThread(self.thread3)
self.thread3.started.connect(obj3.run)
self.thread3.start()
self.thread4 = QThread()
obj4 = D()
obj4.moveToThread(self.thread4)
self.thread4.started.connect(obj4.run)
self.thread4.start()
app = QApplication(sys.argv)
w = window1()
w.show()
sys.exit(app.exec_())
當然可以!謝謝。 – Ninga
但如果我有很多線程,在將它們存儲在諸如self._threads之類的列表中後,如何在完成後將它們刪除? – Shuman
@Shuman請[問一個新問題](http://stackoverflow.com/questions/ask)。這不是真正的拓展地點,答案可能取決於您的具體情況。 –