首页 > 代码库 > code
code
using System;
using System.Threading;
namespace ThreadLocalTest
{
public class MyObject
{
public static MyObject GetCurrentThreadMyObject(String name)
{
if (CurrentThread<MyObject>.ThreadLocal.Value =http://www.mamicode.com/= null) {
CurrentThread<MyObject>.ThreadLocal.Value = http://www.mamicode.com/new MyObject(name);
}
return CurrentThread<MyObject>.ThreadLocal.Value;
}
String _name;
byte[] _bs;
public MyObject(String name)
{
_name = name;
Console.WriteLine("create MyObject.name=" + name);
_bs = new byte[(1024 * 1024 * 100)];
for (int i = 0; i < _bs.Length; i++) {
_bs[i] = 3;
}
}
~MyObject()
{
// Dispose();
Console.WriteLine("~MyObject");
}
}
public class CurrentThread<T>
{
public static readonly ThreadLocal<T> ThreadLocal
= new ThreadLocal<T>(true);
}
class Program
{
static void test1()
{
Thread th1 = new Thread((state) => {
var obj = MyObject.GetCurrentThreadMyObject("obj1");
var obj2 = MyObject.GetCurrentThreadMyObject("obj1");
Console.WriteLine(object.ReferenceEquals(obj,obj2));
Console.WriteLine("t1.id=" + Thread.CurrentThread.ManagedThreadId);
CurrentThread<MyObject>.ThreadLocal.Value=http://www.mamicode.com/null; CurrentThread
//GC.Collect();
//Thread.CurrentThread.Abort();
});
th1.Start();
Thread th2 = new Thread((state) => {
var obj = MyObject.GetCurrentThreadMyObject("obj2");
var obj2 = MyObject.GetCurrentThreadMyObject("obj2");
Console.WriteLine(object.ReferenceEquals(obj,obj2));
Console.WriteLine("t2.id=" + Thread.CurrentThread.ManagedThreadId);
CurrentThread<MyObject>.ThreadLocal.Value=http://www.mamicode.com/null;
CurrentThread<MyObject>.ThreadLocal.Values.Clear();
// GC.Collect();
;
//Thread.CurrentThread.Abort();
});
th2.Start();
Thread th3 = new Thread((state) => {
var obj = MyObject.GetCurrentThreadMyObject("obj3");
var obj2 = MyObject.GetCurrentThreadMyObject("obj3");
Console.WriteLine(object.ReferenceEquals(obj,obj2));
Console.WriteLine("t3.id=" + Thread.CurrentThread.ManagedThreadId);
CurrentThread<MyObject>.ThreadLocal.Value=http://www.mamicode.com/null;
CurrentThread<MyObject>.ThreadLocal.Values.Clear();
//GC.Collect();
;
//Thread.CurrentThread.Abort();
});
th3.Start();
Thread.Sleep(8000);GC.Collect();
GC.Collect(2);
}
public static void Main(string[] args)
{
test1();
Console.ReadKey(true);
}
}
}
code