3,664 views
この記事は最終更新から 2247日 が経過しています。
threading.Thread のサブクラスとして HelloThread を作る。
実行されると文字列を作って出力するだけの処理を実装する。
from threading import Thread class HelloThread( Thread ): def __init__( self, n ): Thread.__init__(self) self.n = n def run(self): self.msg = 'Hello! I am %s.' % self.n
スレッドを3個起動してみる。
if __name__ == '__main__':
names = ['aaa','bbb','ccc']
ths = []
for name in names:
th = HelloThread(name)
ths.append(th)
for i in range(len(ths)):
ths[i].start()
res = []
for i in range(len(ths)):
ths[i].join()
res.append(ths[i].msg)
print res
これらを hello.py に記述し、実行した結果は以下の通り。
[user@]$ python hello.py ['Hello! I am aaa.', 'Hello! I am bbb.', 'Hello! I am ccc.']
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2025-12-14: 0回 2025-12-13: 0回 2025-12-12: 0回 2025-12-11: 2回 2025-12-10: 0回 2025-12-09: 0回 2025-12-08: 1回