Wil*_*iam 1 c# concurrency multithreading
看这里:
static void Main(string[] args)
{
test p = new test();
new Thread(() => p.SayHello("Thread One")).Start();
new Thread(() => p.SayHello("Thread Two")).Start();
}
Run Code Online (Sandbox Code Playgroud)
然后:
class test
{
public void SayHello(string data)
{
int i = 0;
while (i < 50)
{
Console.WriteLine("Hello from " + data);
i++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么第二个线程没有将变量重置i为0?搞乱它在第一个线程上运行的while循环?
这是因为int i是一个局部变量.如果你把它作为静态的类,而不是局部变量,它将被重置.在这种情况下,变量与每个线程隔离.
例:
static void Main(string[] args)
{
test p = new test();
new Thread(() => p.SayHello("Thread One")).Start();
new Thread(() => p.SayHello("Thread Two")).Start();
}
public class test
{
static int i = 0;
public static void SayHello(string data)
{
i = 0;
while (i < 50)
{
Console.WriteLine("Hello from " + data);
i++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |