[英]Multithreading in c# Monitor class
Why do i get the output 1,1,2,3,4,5,6,7,8,9,10 when i use value as lokalvar and the correct ouput 1,2,3,4,5,6,7,8,9,10 when "value" is membervar?当我使用值作为 lokalvar 和正确的输出 1,2,3,4,5,6,7 时,为什么会得到输出 1,1,2,3,4,5,6,7,8,9,10 ,8,9,10 当“值”是成员变量时?
i cant figure out why this happens.我无法弄清楚为什么会发生这种情况。 Thanks for any explanantions ;)
感谢您的任何解释;)
class Beispiel_3
{
int value = 0;
public void Execute_Threads()
{
// why is the out put wrong when i ise the varibale "value" here?
//===============================================================
while (true)
{
Monitor.Enter(this);
value++;
if (value > 20)
break;
Console.WriteLine("Zahl = {0} | Thread = {1}", value, Thread.CurrentThread.GetHashCode().ToString());
Monitor.Exit(this);
}
}
public void Execute_MainThread()
{
Thread thread1, thread2;
thread1 = new Thread(Execute_Threads);
thread2 = new Thread(Execute_Threads);
thread1.Start();
thread2.Start();
Console.ReadLine();
}
static void Main(string[] args)
{
Beispiel_3 bsp3 = new Beispiel_3();
bsp3.Execute_MainThread();
}
You have one class Beispiel_3
in which you start two threads.您有一个类
Beispiel_3
,您可以在其中启动两个线程。 If you declare value
as a member of class Beispiel_3
both threads use this one value
and increase it more or less by turns.如果您将
value
声明为类Beispiel_3
的成员,则两个线程都使用这个value
并轮流或多或少地增加它。 If you declare it in your method Execute_Threads
each thread has its own variable value
and always increase only his own variable value
.如果在方法
Execute_Threads
声明它,每个线程都有自己的变量value
并且始终只增加自己的变量value
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.