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

C#多线程共享数据

2004-11-12 18:57 405 查看
顾剑辉(solarsoft)
在多线程编程中,我们经常要使用数据共享.C#中是如何实现的呢?很简单,只要把你要共享的数据设置成静态的就可以了.关键字static .如下:
static Queue q1=new Queue();
static int b=0;
在这里我定义了一个整形变量b和队列q1.
接下去就可以创建多线程代码了.如下:
MyThread myc;
Thread[] myt;
myt=new Thread[10];
myc=new MyThread();
for(int i=0;i<10;++i)
{
myt[i]=new Thread(new ThreadStart(myc.DoFun));
// System.Console.WriteLine("<<{0}>>",myt[i].GetHashCode());
myt[i].Start();
Thread.Sleep(1000);
}
你可能惊奇的发现这里使用了一个类实例myc.在起初的设计中我使用了MyThread数组,对于本例来说这没有什么关系,当线程要使用不同的操作时,那就要使用其他的类实例了.

以下是完整的代码:
using System;
using System.Threading;
using System.Collections;
namespace shareThread
{
class MyThread
{
static Queue q1=new Queue();
static int b=0;

public void DoFun()
{
lock(this)
{
++b;
q1.Enqueue(b);
}
System.Console.WriteLine("B:{0}--------------",b);
PrintValues( q1 );

}

public static void PrintValues( IEnumerable myCollection )
{
System.Collections.IEnumerator myEnumerator = myCollection.GetEnumerator();
while ( myEnumerator.MoveNext() )
Console.Write( "/t{0}", myEnumerator.Current );
Console.WriteLine();
}

}

/// <summary>
/// Class1 的摘要说明。
/// </summary>
class ClassMain
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
MyThread myc;
Thread[] myt;

myt=new Thread[10];
myc=new MyThread();
for(int i=0;i<10;++i)
{

myt[i]=new Thread(new ThreadStart(myc.DoFun));
// System.Console.WriteLine("<<{0}>>",myt[i].GetHashCode());
myt[i].Start(); //线程运行
Thread.Sleep(1000);//主线程睡眠
}
System.Console.Read();//等待完成,dos窗口不会马上关闭了.
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: