请写出python3多线程测试
时间: 2023-09-09 13:14:05 浏览: 48
我可以为您提供一个python3多线程测试的代码示例,如下:
```
import threading
def worker(num):
"""线程要执行的任务"""
print('Worker %d is running' % num)
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print('All workers have finished')
```
这个示例代码创建了5个线程,并且每个线程都会打印出自己的编号。程序会等待所有线程执行完毕后才会输出"All workers have finished"。
相关问题
请用python写出多线程爬虫
好的,以下是一个简单的多线程爬虫的 Python 代码示例:
```python
import threading
import requests
class MyCrawler(threading.Thread):
def __init__(self, url):
threading.Thread.__init__(self)
self.url = url
def run(self):
response = requests.get(self.url)
print(response.text)
if __name__ == '__main__':
urls = ['https://www.baidu.com', 'https://www.google.com', 'https://www.bing.com']
threads = []
for url in urls:
t = MyCrawler(url)
threads.append(t)
t.start()
for t in threads:
t.join()
```
以上代码中,我们定义了一个 `MyCrawler` 类,继承自 `threading.Thread` 类,实现了 `run()` 方法。在 `run()` 方法中,我们使用 `requests` 库发送 HTTP 请求,获取网页内容并输出。
在主函数中,我们创建了多个 `MyCrawler` 线程,并将它们加入到 `threads` 列表中。然后,我们启动每个线程,等待所有线程执行完毕后再退出程序。
python ping3多线程ping测试
可以使用Python的ping3库和threading库来实现多线程ping测试。下面是一个简单的示例代码:
```python
import ping3
import threading
HOSTS = [
"www.google.com",
"www.baidu.com",
"www.github.com",
"www.stackoverflow.com"
]
class PingThread(threading.Thread):
def __init__(self, host):
threading.Thread.__init__(self)
self.host = host
def run(self):
response_time = ping3.ping(self.host)
if response_time is not None:
print(f"{self.host} is alive. Response time: {response_time} ms")
else:
print(f"{self.host} is down.")
if __name__ == "__main__":
threads = []
for host in HOSTS:
thread = PingThread(host)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
```
这个示例代码会创建多个PingThread线程来分别ping指定的主机,当收到响应时,会输出相应的信息。可以根据需要修改HOSTS列表中的主机名。