用50个多线程打印200个数字,一次同时打印50个,带进度条的简单的UI。
import threading 多线程的库,导入多线程
def show():
for i in range(0, 50): # 线程50个
thread = threading.Thread(target=run_thread, args=('thread-' + str(i),))
thread.start()
一个带进度条的简单的UI
打印效果如下
F:\pythonProject\venv\Scripts\python.exe F:/pythonProject/demo1.py
thread-0 : 1
thread-1 : 2
thread-2 : 3
thread-3 : 4
thread-4 : 5
thread-5 : 6
thread-6 : 7
thread-7 : 8
thread-8 : 9
thread-9 : 10
完整的代码如下
# coding:utf-8
import threading
import time
import tkinter
import tkinter.ttk
# ===============普通UI==================
window = tkinter.Tk()
window.title('def多线程') # 窗口的标题
window.geometry('200x100') # 窗口的大小
progressbarOne = tkinter.ttk.Progressbar(window)
progressbarOne.pack(pady=20)
progressbarOne['maximum'] = 100 # 进度值最大值
progressbarOne['value'] = 0 # 进度值初始值
# ===============普通UI==================
lock = threading.Lock()
c = 0
list3=[]
def show():
for i in range(0, 50): # 线程50个
thread = threading.Thread(target=run_thread, args=('thread-' + str(i),))
thread.start()
def run_thread(n):
global c
while c < 200:
lock.acquire()
c += 1
print(n, ':', c)
lock.release()
time.sleep(2) # 在这个地方添加实际的逻辑.....
lock.acquire()
progressbar()
lock.release()
def progressbar():
list3.append(c)
l = len(list3)
for i in range(0, int(l / 200 * 100)):
progressbarOne['value'] = i + 1 # 每次更新加1
window.update() # 更新画面
button = tkinter.Button(window, text='Running', command=show)
button.pack(pady=5)
window.mainloop()
点击画面执行,执行def show():,多线程开始执行,每一个多线程执行def run_thread(n):,在此过程中进度条不断更新def progressbar():,一个基本的框架。
需要注意的是lock = threading.Lock()
lock.release() time.sleep(2) # 在这个地方添加实际的逻辑..... lock.acquire()
完成对线程池的上锁,要不然输出就会乱。
对于学习python我的态度和我的ID一样。“国服小闲鱼请战”。