C # multi-thread sharing data

xiaoxiao2021-03-06  71

Gu Jianhui In multi-threaded programming, we often use data sharing. How is it implemented in C #? Very simple, just set the data you want to share into static, you can. Keyword static. As follows: static Queue Q1 = new queue (); static int b = 0; here I defined a shaped variable B and queue Q1. You can create multi-threaded code. As follows: 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);} You may be surprised to find a class here Example Myc. In the initial design I used mythread array, this is nothing to do with this example, when thread uses different operations, then use other class instances. Here is the complete code: useing System; using system.threading; using system.collections;

Namespace Sharathread {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 ();

}

///

/// Class1 summary description. /// class classmain {/// /// The primary invested point of the application. /// [stathread] static void main (String [] args) {mythread myc; thread [] myt;

Myt = new thread [10]; myc = new mythread (); for (int i = 0; i <10; i) {

转载请注明原文地址:https://www.9cbs.com/read-92333.html

New Post(0)