面试题答案
一键面试import threading
import time
class FileReader:
def __init__(self, file_path):
self.file_path = file_path
self.lock = threading.Lock()
def read_file(self):
with self.lock:
try:
with open(self.file_path, 'r') as file:
content = file.read()
print(f"线程 {threading.current_thread().name} 读取到内容: {content}")
except FileNotFoundError as e:
print(f"线程 {threading.current_thread().name} 捕获到异常: {e}")
except Exception as e:
print(f"线程 {threading.current_thread().name} 捕获到其他异常: {e}")
if __name__ == "__main__":
file_path = "test.txt"
reader = FileReader(file_path)
threads = []
for i in range(3):
thread = threading.Thread(target=reader.read_file)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
在上述代码中:
FileReader
类封装了文件读取的操作,并使用threading.Lock
来确保多线程环境下对文件操作的资源安全。- 使用
with open
语句来读取文件,这可以保证无论在读取过程中是否发生异常,文件都会被正确关闭。 - 在
read_file
方法中,使用try - except
块捕获可能发生的异常,并在捕获到异常时打印相应的信息。
这样既确保了文件资源被正确关闭,又保证了多线程环境下的资源安全。