zoukankan      html  css  js  c++  java
  • 在项目中 将秒杀的时候锁定线程并将线程操作的ID写入txt文件中 (例子)

    锁定线程,进行单线程操作的时候,应使用以下操作方法锁定:
    private readonly static Object thisLock = new Object();
     lock (thisLock)
    {
    ...
    }
    //
    private void writeLog(Exception e)
            {
                FileStream fs = new FileStream("d:/ceshixiancheng.txt", FileMode.Append);
                
                //获得字节数组
                byte[] data = new UTF8Encoding().GetBytes(e.Message);
                //开始写入
                fs.Seek(0, SeekOrigin.End);
                fs.Write(data, 0, data.Length);
                var str = "
    ";
                byte[] data1 = new UTF8Encoding().GetBytes(str);
                fs.Write(data1, 0, data1.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }
    
    //使用时的调用:
      writeLog(new Exception("线程:" + Thread.CurrentThread.ManagedThreadId + "进来了!"));
    View Code

    以上为在做秒杀时 锁定线程,防止库存溢出的一个测试,测试是不是将线程锁定了,正常情况,线程锁定后,输出到txt文档的内容都是成对的,一进一出。如果不是则说明县城没有锁死.另外注意需要将txt文档的权限给了,否则会提示没有权限。

  • 相关阅读:
    解决在linux环境安装setuptools的相关错误
    sql根据最小值去重
    linux重新安装python
    python 进阶(转自http://python.jobbole.com/82633/)
    redis做消息列队
    下载安装windows版Redis
    vue-cli 结构
    vue-cli 安装
    [python]爬虫学习(三)糗事百科
    jquery基础
  • 原文地址:https://www.cnblogs.com/WZH75171992/p/4962858.html
Copyright © 2011-2022 走看看