3,768 views
この記事は最終更新から 2426日 が経過しています。
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除外簡易実装済2026-06-10: 1回 2026-06-09: 0回 2026-06-08: 0回 2026-06-07: 1回 2026-06-06: 0回 2026-06-05: 0回 2026-06-04: 0回