---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------interlocked(互锁)
interlocked类的部分方法
read() 读取计数器的值
Increment() 使计数器增加1
Decrement()使计数器减小1;
Add() 使计数器增加指定的值
Exchange() 把计数器设置为指定的值
CompareExchange() 先把计数器和某个值进行比较,若相等,就把计数器设为指定值
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace 线程同步interlocked
{
class Program
{
private static char result;
private static string a = "青青子衿,悠悠我心!";
static void Main(string[] args)
{
ThreadStart ts=write;
ThreadStart ts2 = read;
Thread readThread = new Thread(ts2);
Thread writeThread = new Thread(ts);
writeThread.Start();
readThread.Start();
}
static void write()
{
for (int i = 0; i < a.Length; i++)
{
result = a[i];
Thread.Sleep(20);
}
}
static void read()
{
for (int i = 0; i < a.Length; i++)
{
char b = result;
Console.Write(b);
Thread.Sleep(20);
}
}
}
}
这样输出后会有错误
使用互锁后就可以正常输出了
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace 线程同步interlocked
{
class Program
{
private static char result;
private static string a = "青青子衿,悠悠我心!";
static void Main(string[] args)
{
ThreadStart ts=write;
ThreadStart ts2 = read;
Thread readThread = new Thread(ts2);
Thread writeThread = new Thread(ts);
writeThread.Start();
readThread.Start();
}
static long num = 0;
static void write()
{
for (int i = 0; i < a.Length; i++)
{
//while (Interlocked.Read(ref num) == 1)
//{ Thread.Sleep(10); }
while (num == 1)
{ Thread.Sleep(10); }
result = a[i];
//Interlocked.Increment(ref num);
num += 1;
}
}
static void read()
{
for (int i = 0; i < a.Length; i++)
{
//while (Interlocked.Read(ref num) == 0)
//{ Thread.Sleep(10); }
while (num == 0)
{ Thread.Sleep(10); }
char b = result;
Console.Write(b);
num = num - 1;
//Interlocked.Decrement(ref num);
}
}
}
}
---------------------- Windows Phone 7手机开发、 .Net培训、期待与您交流! ----------------------详细请查看: http://net.itheima.com/