|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
以前学了大概半年时间的asp(没有机会做大系统,最多是自己对公司系统做些调整和修改还有一些小程序)。应该说开始接触asp.net是今年元月5号的事。现在很想把公司的系统重新用.net来架构,却不知道如何下手。编程|多线程//DeadLockSample.cs
//剖析一下为何会产生逝世锁?- usingSystem;usingSystem.Threading;publicclassTest{staticreadonlyobjectfirstLock=newobject();staticreadonlyobjectsecondLock=newobject();staticvoidMain(){newThread(newThreadStart(ThreadJob)).Start();//Waituntilwerefairlysuretheotherthread//hasgrabbedfirstLockThread.Sleep(500);Console.WriteLine("LockingsecondLock");lock(secondLock){Console.WriteLine("LockedsecondLock");Console.WriteLine("LockingfirstLock");lock(firstLock){Console.WriteLine("LockedfirstLock");}Console.WriteLine("ReleasedfirstLock");}Console.WriteLine("ReleasedsecondLock");}staticvoidThreadJob(){Console.WriteLine(" LockingfirstLock");lock(firstLock){Console.WriteLine(" LockedfirstLock");//Waituntilwerefairlysurethefirstthread//hasgrabbedsecondLockThread.Sleep(1000);Console.WriteLine(" LockingsecondLock");lock(secondLock){Console.WriteLine(" LockedsecondLock");}Console.WriteLine(" ReleasedsecondLock");}Console.WriteLine(" ReleasedfirstLock");}}LockingfirstLock
- LockedfirstLock
- LockingsecondLock
- LockedsecondLock
- LockingfirstLockLockingsecondLock
复制代码 因应之道,利用Queue和Monitor:
//QueueMonitorThread.cs- usingSystem;usingSystem.Collections;usingSystem.Threading;publicclassTest{staticProducerConsumerqueue;staticvoidMain(){queue=newProducerConsumer();newThread(newThreadStart(ConsumerJob)).Start();Randomrng=newRandom(0);for(inti=0;i<10;i++){Console.WriteLine("Producing{0}",i);queue.Produce(i);Thread.Sleep(rng.Next(1000));}}staticvoidConsumerJob(){//Makesurewegetadifferentrandomseedfromthe//firstthreadRandomrng=newRandom(1);//Wehappentoknowweveonlygot10//itemstoreceivefor(inti=0;i<10;i++){objecto=queue.Consume();Console.WriteLine(" Consuming{0}",o);Thread.Sleep(rng.Next(1000));}}}publicclassProducerConsumer{readonlyobjectlistLock=newobject();Queuequeue=newQueue();publicvoidProduce(objecto){lock(listLock){queue.Enqueue(o);if(queue.Count==1){Monitor.Pulse(listLock);}}}publicobjectConsume(){lock(listLock){while(queue.Count==0){Monitor.Wait(listLock);}returnqueue.Dequeue();}}}Producing0Consuming0
- Producing1Consuming1
- Producing2Consuming2
- Producing3Consuming3
- Producing4
- Producing5Consuming4
- Producing6Consuming5
- Consuming6
- Producing7Consuming7
- Producing8Consuming8
- Producing9Consuming9
复制代码 我也不知道,我原来理解的,NET就是C++编程,只是与JAVA相对,呵呵。以为.ET就是高级C++编程。 |
|