pyQt5线程池使用

#! /usr/bin/env python
#coding=utf-8
import threading

from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QProgressBar
import sys
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        tasks = []
        for counter in range(1,101):
            task=Tasks(counter)
            task.start()
            tasks.append(task)
        for t in tasks:
            t.notify()
            time.sleep(0.05)
        Tasks.wait()
        print ("退出线程:" + self.name)

class Thread(QtCore.QRunnable):
    
    def __init__(self,num):
       super(Thread,self).__init__()
       self.num=num
    def run(self):
       print("Running Thread #%d" % self.num)
       #time.sleep(2)
       #some say time.sleep will froze entire main thread(thus not recommended)

      QtCore.QThread.msleep(80)
       
#自定义信号槽如何把持http://www.cnblogs.com/codeio/archive/2011/08/30/2159030.html
class Tasks(QtCore.QObject):
    
    signal=QtCore.pyqtSignal(int)
    #signal must be declared outside the constructor but within class.
    def __init__(self,num):
       super(Tasks,self).__init__()
       self.pool=QtCore.QThreadPool.globalInstance()
       self.num=num
       self.signal.connect(proBar.setValue)
       #signal slot connection.watch out for parameter matching(type & count).    
    
    def start(self):
       threadIns=Thread(self.num)
       self.pool.start(threadIns)
    
    def notify(self):
        self.signal.emit(self.num)
    
    @staticmethod
    def wait():
       QtCore.QThreadPool.globalInstance().waitForDone()
       

       
if __name__=="__main__":
   App=QApplication(sys.argv)
   print(QtCore.QThread.currentThreadId())
    
   proBar=QProgressBar()
   proBar.setWindowTitle("Nuclear Launch Progression")
   proBar.setValue(0)
   proBar.setGeometry(200,500,1000,30)
   proBar.show()

   # 这里在子线程里异步启动QThreadPool,并等待线程池结束,如果不异步启动的话会阻塞ui主线程
   th = myThread(1, 'thread-1', 1)
   th.start()
   sys.exit(App.exec_())

你可能感兴趣的:(python,qt,p2p,蓝桥杯)