我已经从此页面或其他页面上读了许多有关此问题的文章,但仍然找不到真实的答案。根据这些答案,(静态/实例)方法内部创建的所有变量都应安全。不幸的是,这无法正常工作。
我有此代码:
public static void TestThreadSafetyOfInsideVariableOfStaticMethod()
{
Thread t1 = new Thread(staticClass.Test) { Name = "t1" };
Thread t2 = new Thread(staticClass.Test) { Name = "t2" };
Thread t3 = new Thread(staticClass.Test) { Name = "t3" };
Thread t4 = new Thread(staticClass.Test) { Name = "t4" };
t1.Start(); t2.Start(); t3.Start(); t4.Start();
}
public static class staticClass
{
public static void Test()
{
for (int i = 1; i < 11; i++)
{
FileStream fs = new FileStream("C:\test.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
byte[] bytesToWrite = Encoding.UTF8.GetBytes(Thread.CurrentThread.Name + " is currently writing its line " + i + ".rn");
fs.Write(bytesToWrite, 0, bytesToWrite.Length);
fs.Close();
fs.Dispose();
Thread.Sleep(500);
}
}
}
当我运行testThreadSafetyOfinSideVariable ofstaticMethod时,文本文件中的输出是:
T2目前正在编写其第1行。
T3目前正在编写其第1行。
T4目前正在编写其第1行。
T1目前正在编写其第2行。
T2目前正在编写其第2行。
T4目前正在编写其第2行。
T2目前正在编写其第3行。
T1目前正在编写其第3行。
T4目前正在编写其第3行。
T4目前正在编写其第4行。
T4目前正在编写其第5行。
T1目前正在编写其第6行。
T1目前正在编写其第7行。
T1目前正在编写其第8行。
T2目前正在编写其第9行。
T1目前正在编写其第9行。
T3目前正在编写其第9行。
T4目前正在编写其第10行。
- 文件的结尾。
我希望每个线程都会在其循环中编写自己的行,因此在方法内部的for循环中不共享" I"变量。他们为什么共享这个"我"变量?
我是否必须将所有静态方法锁定在整个项目中?而参数呢,线程也共享(我不会显示代码,但我已经对其进行了测试)。
问题不是共享变量i
,而是共享文件"C:\test.txt"
。同时,您有四个线程写作。这些写入绝对没有同步,因此,当几个线程试图附加其"tX is currently writing its line Y"
时,一个将会赢得胜利,其余的将看到它们的输出下降。
您可以通过在访问文件时在线程之间建立适当的同步来解决此问题,以防止同时附加。