有关线程的一些小记录

36 篇文章 0 订阅
使用继承Thread的方式使用线程的话,不能共享资源,实现Runnable的方式,可以实现资源共享。
工作中尽量使用线程池的方式进行线程的创建。
使用线程池可以防止线程无限制的扩张导致服务宕机,另外节省了线程的创建、销毁的时间成本。要知道,对于衡量一个程序的好坏,时间长短是很重要的指标,稍微规模大一点的公司,接口耗时不达标是不行的。
//申请线程工厂,为线程命名
 ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-methsName-call-runner-%d").build();
 //创建线程池
 ExecutorService excutor = new ThreadPoolExecutor(3, 5, 0L,TimeUnit.SECONDS, new ArrayBlockingQueue<>(5), threadFactory, new ThreadPoolExecutor.AbortPolicy());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Python 中,可以使用 `logging` 模块记录日志。如果需要在多线程环境下记录日志,可以使用 `concurrent_log_handler` 模块来实现。 首先需要安装 `concurrent_log_handler` 模块: ``` pip install concurrent_log_handler ``` 然后,可以使用以下代码来记录日志: ```python import logging from concurrent_log_handler import ConcurrentRotatingFileHandler import threading # 创建日志记录器 logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # 创建文件处理器 handler = ConcurrentRotatingFileHandler(filename='example.log', mode='a', maxBytes=1024, backupCount=3) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # 将处理器添加到记录器 logger.addHandler(handler) # 多线程记录日志 def worker(): logger.debug('Debug message from thread {0}'.format(threading.current_thread().name)) logger.info('Info message from thread {0}'.format(threading.current_thread().name)) logger.warning('Warning message from thread {0}'.format(threading.current_thread().name)) logger.error('Error message from thread {0}'.format(threading.current_thread().name)) logger.critical('Critical message from thread {0}'.format(threading.current_thread().name)) threads = [] for i in range(10): t = threading.Thread(target=worker) threads.append(t) t.start() for t in threads: t.join() ``` 上面的代码中,创建了一个 `ConcurrentRotatingFileHandler` 类实例化的文件处理器,它可以在多线程环境下安全地写入日志文件。然后,将处理器添加到日志记录器中,并使用多线程记录日志。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

还算善良_

如果对你的工作有所帮助,拜托啦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值