Multi-thread variable memory allocation and multi-thread Variable Allocation
using System;using System.Collections.Generic;using System.Text;using System.Threading;using System.Diagnostics;namespace TestMultiThread{ class Program { pp s = new pp(); static void Main(string[] args) { Program dd = new Program(); Thread th; for (int i = 0; i < 10; i++) { th= new Thread(new ThreadStart(dd.Test)); th.Name = i.ToString(); th.Start(); Thread.Sleep(10); } Console.WriteLine("wait 3 seconds"); Console.ReadKey(); } public void Test() { Int32 i = 0; i++; Console.WriteLine("name:{0}/I vaule:{1}", Thread.CurrentThread.Name,i.ToString()); s.ps(); } } class pp { public void ps() { Int32 i=0; Thread.Sleep(3000); i++; Console.WriteLine("ps:name:{0}/i:{1}", Thread.CurrentThread.Name,i.ToString()); } }}
- When N threads are initiated, other classes of methods are called in the thread's method body. These called methods also open up N spaces in the memory, all of which exist independently and interfere with each other.
- When N threads are initiated, the method of each thread opens up new memory space. The local variables in each method body are independent of each other.
Test code:
- Initiate 10 threads. The I value in each thread is 1. It indicates that each thread method has its own memory space.
- Initiate 10 threads, and each thread calls the ps () method again. The ps () method sleeps for 3 seconds, and then prints the information to the console. The display effect is that 10 threads are started. After 3 seconds, the information in ps () is instantly printed, indicating that other methods are called in the thread method body, these methods also allocate Multiple Memory Spaces. If ps () uses the same memory space, console information is printed every 3 seconds.