首页 > 代码库 > 多线程中变量的内存分配

多线程中变量的内存分配

 

  • 发起N个线程,线程的方法体中再调用其他类的方法,这些被调用的方法也会在内存中开辟出N个空间,且都是单独存在,互补干扰。
  • 发起N个线程,每个线程的方法体会开辟新的内存空间,每个方法体中的局部变量是独立存在互补干扰的。

测试代码:

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.ReadKey();        }        public void Test()        {            Int32 i;            //while (true)            //{            //    i = p.ps();            //    Console.WriteLine("I vaule:{0}", i.ToString());            //    Thread.Sleep(1000);            //}            Console.WriteLine("kaishi");            i = s.ps();            Console.WriteLine("name:{0}/I vaule:{1}", Thread.CurrentThread.Name,i.ToString());        }    }    class pp    {        int i = 0;        public Int32 ps()        {                Thread.Sleep(3000);            //String s = Process.GetCurrentProcess().Threads.Count.ToString();            //Console.WriteLine("count:{0}",s);            i++;            Console.WriteLine("ps:name:{0}/I vaule:{1}", Thread.CurrentThread.Name, i.ToString());            return i;        }    }}

 

多线程中变量的内存分配