国产探花免费观看_亚洲丰满少妇自慰呻吟_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窗口不會馬上關閉了.
}
}
}





發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁安市| 工布江达县| 龙江县| 娄底市| 合阳县| 徐州市| 德惠市| 慈溪市| 宜君县| 朝阳区| 宝兴县| 清河县| 固始县| 宜昌市| 高要市| 宝鸡市| 克拉玛依市| 沿河| 阿克苏市| 马公市| 仁怀市| 临沧市| 邵武市| 宣武区| 肇东市| 墨玉县| 子长县| 建昌县| 临朐县| 合水县| 河曲县| 湘潭县| 南充市| 连州市| 资阳市| 阜阳市| 社会| 剑阁县| 乌审旗| 绵阳市| 景东|