# -*- coding:utf-8 -*-
import threading
import queue
import time
import random
from faker import faker
class
mythread
(threading.thread):
''' 執行緒模型
'''def__init__
(self,queue):
threading.thread.__init__(self)
self.queue = queue
defrun
(self):
while
true: # 除非確認佇列中已經無任務,否則時刻保持執行緒在執行
try:
task = self.queue.get(block=false) # 如果佇列空了,直接結束執行緒。根據具體場景不同可能不合理,可以修改
time.sleep(random.random()) # 假設處理了一段時間
print
'task %s done' % task # 提示資訊而已
self.queue.task_done()
except exception,e:
break
class
mythreadpool
():def
__init__
(self,queue,size):
self.queue = queue
self.pool =
for i in range(size):
defjoinall
(self):
for thd in self.pool:
if thd.isalive(): thd.join()
if __name__ == '__main__':
q = queue.queue(10)
fake = faker()
for i in range(5):
q.put(fake.word())
pool = mythreadpool(queue=q,size=2)
pool.joinall()
POSIX執行緒多執行緒例子
include include include include define num threads 6 void thread function void arg int main sleep 1 printf waiting for threads to finish.n for lots of...
多執行緒實例子
class threaddemo1 catch exception e system.out.println main thread.currentthread getname testthread tt new testthread tt.start tt.start tt.start tt.st...
java多執行緒 例子
題目 一共有100個饅頭,40個工人,每個工人最多可以吃3個饅頭,使用多執行緒輸出所有工人吃饅頭的情況。程式很簡單,設計如下 public class mantoudemo class worker extends thread public void run 如果沒吃飽,繼續取饅頭 int t b...