C#多線程共用資料

來源:互聯網
上載者:User
在多線程編程中,我們經常要使用資料共用.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視窗不會馬上關閉了.
}
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.