python中threading的用法
时间: 2023-09-23 17:05:51 浏览: 65
在Python中,使用threading模块可以创建和管理线程。可以通过以下几种方式来使用threading模块:
1. 创建threading.Thread的子类来包装一个线程对象。可以继承threading.Thread类,并重写run()方法来定义线程的执行逻辑。然后通过调用start()方法来启动线程。例如,可以创建一个timer类来实现定时输出的线程:
```python
import threading
import time
class timer(threading.Thread):
def __init__(self, num, interval):
threading.Thread.__init__(self)
self.thread_num = num
self.interval = interval
self.thread_stop = False
def run(self):
while not self.thread_stop:
print('Thread Object(%d), Time:%s' %(self.thread_num, time.ctime()))
time.sleep(self.interval)
def stop(self):
self.thread_stop = True
def test():
thread1 = timer(1, 1)
thread2 = timer(2, 2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
if __name__ == '__main__':
test()
```
[1]
2. 使用thread模块中的start_new_thread()函数来产生新线程。可以通过调用start_new_thread()函数来创建新线程,并传入一个函数和参数来定义线程的执行逻辑。例如,可以创建一个timer函数来实现定时输出的线程:
```python
import time
import thread
def timer(no, interval):
cnt = 0
while cnt < 10:
print('Thread:(%d) Time:%s' %(no, time.ctime()))
time.sleep(interval)
cnt += 1
thread.exit_thread()
def test():
thread.start_new_thread(timer, (1, 1))
thread.start_new_thread(timer, (2, 2))
if __name__ == '__main__':
test()
```
[3]
此外,threading模块还提供了其他方法和类,可以帮助我们更好地使用和管理线程。可以参考官方文档了解更多信息:http://www.python.org/doc/2.5.2/lib/module-threading.html。[2]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)