我想实现把一个对象锁定当执行完操作的时候解锁,在执行此操作过程中其他线程不允许读写此对象,一下是代码.但是发现无法实现想要的功能,请大家指教
public class Test { static Test _temp = new Test(); public object X { get; set; } public static void Get(object n) { lock (_temp) { Console.WriteLine(string.Format("{0}__X初始值为:{1}", Thread.CurrentThread.Name, _temp.X)); Console.WriteLine(string.Format("{0}__传入值为:{1}", Thread.CurrentThread.Name, n)); _temp.X = n; Thread.Sleep(8); Console.WriteLine(string.Format("{0}__赋值完毕为:{1}", Thread.CurrentThread.Name, _temp.X)); Console.WriteLine("==============="); } } public static void SetValue(object n) { _temp.X = n; } } class Program { static void Main(string[] args) { Thread[] thds = new Thread[10]; for (int i = 0; i < 10; i++) { thds[i] = new Thread(new ParameterizedThreadStart(Test.Get)); thds[i].Name = "thread" + i; } Thread[] thds2 = new Thread[10]; for (int i = 0; i < 10; i++) { thds2[i] = new Thread(new ParameterizedThreadStart(Test.SetValue)); } Random ran = new Random(); for (int i = 0; i < 10; i++) { thds[i].Start(i); thds2[i].Start(ran.Next(100, 1000)); } Console.Read(); } }
逻辑问题
Get的锁没问题,主要是SetValue
谢谢,懂了
private static object _locker = new object(); lock(_locker) { }