java多线程同时读取一个文件,这个方法可行吗?

java多线程同时读取一个文件,这个方法可行吗?,第1张

不可行。每次读取文件都需要创建缓存文件流,很占内存,而且多次读取实际上也是一个文件,还不如直接读取文件,之后通过条件多次获取需要的内容来的实际。

可以通过BufferedReader 流的形式进行流缓存,之后通过readLine方法获取到缓存的内容。

BufferedReader bre = null

try {

String file = "D:/test/test.txt"

bre = new BufferedReader(new FileReader(file))//此时获取到的bre就是整个文件的缓存流

while ((str = bre.readLine())!= null) // 判断最后一行掘拦不存在,为空结束循环

{

System.out.println(str)//原样输出读到的内容,此处可以添加条件进行不同的处理

};

备注: 流用完之判塌胡后衫猜必须close掉,如上面的就应该是:bre.close(),否则bre流会一直存在,直到程序运行结束。

测试方法:开两个线程读写同一个文件。主要是FileStream对象里面早困唤的三个参数FileMode,FileAccess,FileShared的枚举值选择。

class Program

{

private static string path = AppDomain.CurrentDomain.BaseDirectory + "cache.xml"

static void Main(string[] args)

{

Thread th1 = new Thread(Writexml)

th1.Start()

Thread th2 = new Thread(Readxml)

th2.Start()

}

static void Writexml()

{

while (true)

{

StringBuilder sb = new StringBuilder()

sb.AppendLine(String.Format("<Cache name=\"{0}\">", "aa"))

sb.AppendLine(String.Format("<Subkey name=\"{0}\">", "bb"尺嫌))

sb.AppendLine(String.Format("<Data><![CDATA[{0}]]></Data>", "{\"Value\":[{\"BindingType\":\"net.tcp\",\"ServiceIP\":\"192.168.1.226\",\"ServicePort\":\"9420\",\"SvcPath\":\陆凯"HotelPayNotifyService.svc\"}]}"))

sb.AppendLine("</Subkey>")

sb.AppendLine("</Cache>")

using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))

{

byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString())

fs.Write(bytes, 0, bytes.Length)

}

Thread.Sleep(200)

}

}

static void Readxml()

{

while (true)

{

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))

{

XmlDocument doc = new XmlDocument()

doc.Load(fs)

XmlNode dataNode = doc.SelectSingleNode(String.Format("Cache/Subkey[@name='{0}']/Data", "bb"))

Console.WriteLine(dataNode.InnerText)

}

Thread.Sleep(100)

}

}

}

这样的情况还是比较正常,在几百毫秒的情况下,这样的能够满足大部分要求了。

另:还遇到了关于Dictionary并发的问题,声明了一个静态的Dictionary对象,通过深度复制来保证并发读写不会抛异常。处理的代码如下:

Dictionary<String, Dictionary<String,

Object>>newdic = new Dictionary<string, Dictionary<string,

object>>()

using (MemoryStream ms = new MemoryStream())

{

IFormatter formator = new BinaryFormatter()

formator.Serialize(ms, dic)

ms.Seek(0, SeekOrigin.Begin)

newdic=(formator.Deserialize(ms) as Dictionary<String,Dictionary<String,Object>>)

}

在Linux下,我们可以使用多线程并发执行sql文件命令。以下是一个简单的示例:

1. 首先,创建一个包含需要执行的SQL文件路径的文本文件,名为file_list.txt:

```

/home/user/sql/file1.sql

/home/user/sql/file2.sql

/home/user/sql/file3.sql

```

2. 然后,使用xargs和并发执行工具parallel来读取file_list.txt中的每个文件路径,并执行mysql命令:

```

cat file_list.txt | xargs -I {} -P 4 sh -c 'mysql -u [username] -p[password] [database] <{}'

```

这个命令将执行file_list.txt中指定的每个SQL文件,并且允许同时执行4个进程(-P 4参数)。你需要将[username]、[password]和[database]替换为你的数据库用户名、密码和数据库名。

3. 如果你想输出执行结果或错误信息到文件中,可以添加重定向 *** 作符">"或"2>"。例如:

```

cat file_list.txt | xargs -I {} -P 4 sh -c 'mysql -u [username] -p[password] [database] <{} >{}.out 2>{}.err'

```

这将把每个SQL文件执行后的输出结果和错误信老模历息保存到它们各自的".out"和".err"文件中。

注意:在码隐执行这种批量处理任务时,请确保你的系统有足够的资源支持多线程和并发执行侍搜。同时,也要注意对于生产环境的数据库,一定要谨慎 *** 作,避免数据丢失或损坏。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12273809.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存