国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

C#多線程共享數據

2024-07-21 02:30:03
字體:
來源:轉載
供稿:網友
在多線程編程中,我們經常要使用數據共享.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窗口不會馬上關閉了.
}
}
}





發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阳山县| 天台县| 栖霞市| 伊宁市| 江西省| 黎平县| 旬阳县| 县级市| 绥德县| 西丰县| 石渠县| 呼和浩特市| 岗巴县| 逊克县| 利川市| 景泰县| 阿合奇县| 岢岚县| 台北县| 宜川县| 始兴县| 新乡县| 大连市| 玛多县| 章丘市| 香港| 米易县| 临夏县| 湘阴县| 中超| 嵊州市| 罗江县| 郑州市| 伽师县| 泽州县| 金昌市| 高阳县| 交城县| 新宁县| 嘉善县| 兴文县|