您的位置:首页 > 编程语言 > C#

C# 线程同步

2013-10-13 23:21 375 查看
using System;
using System.Threading;
using System.Text;
using System.Threading.Tasks;

//多线程调试: 2013.10.08
//转自 http://www.cnblogs.com/yank/p/3227324.html namespace ThreadExample
{
class SpinLockSample
{
public static void Test()
{
SpinLock sLock = new SpinLock();
StringBuilder sb = new StringBuilder();
Action action = () =>
{
bool gotLock = false;
for (int i = 0; i < 5; i++)
{
gotLock = false;
try
{
sLock.Enter(ref gotLock);
sb.Append(i.ToString());
}
catch (System.Exception ex)
{

}
finally
{
if (gotLock)
{
sLock.Exit();
}
}
}
};
//多线程调用action
Parallel.Invoke(action,action,action);
Console.WriteLine("Ouput {0}",sb.ToString());
}
}

class App
{
private static object UsingPrinterLocker = new object();
private static Mutex mutex = new Mutex();

public static void Main()
{
SpinLockSample.Test();
//TestPrint();
}

public static void TestPrint()
{
Thread thread;
Random random = new Random();

for (int i = 0; i < 10;i++ )
{
thread = new Thread(MyThreadProc);
thread.Name = string.Format("Thread {0}", i);
Thread.Sleep(random.Next(3));
thread.Start();
}
}

public static void MyThreadProc()
{
//UserPrinter();
//UsePrinterWithMutex();
UsePrinterWithMoniter();
}

public static void UsePrinterWithMutex()
{
mutex.WaitOne();
try
{
Console.WriteLine("{0} acquired thd lock", Thread.CurrentThread.Name);
Thread.Sleep(2000);
Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name);
}
catch (System.Exception ex)
{

}
finally
{
mutex.ReleaseMutex();
}
}

public static void UsePrinterWithMoniter()
{
System.Threading.Monitor.Enter(UsingPrinterLocker);
try
{
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
Thread.Sleep(500);
Console.WriteLine("{0} exit lock", Thread.CurrentThread.Name);
}
catch (System.Exception ex)
{

}
finally
{
System.Threading.Monitor.Exit(UsingPrinterLocker);
}
}

public static void UserPrinter()
{
lock (UsingPrinterLocker)
{
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
Thread.Sleep(500);
Console.WriteLine("{0} exiting lock.", Thread.CurrentThread.Name);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: