C#多线程共享数据

在多线程编程中,我们经常要使用数据共享.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窗口不会马上关闭了.
}
}


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值