In multi-threaded programming, we often need to use data sharing. C # in how to implement it? You just need to set the data you want to share to static. The keyword static is as follows:
Static queue Q1 = new Queue ();
Static int B = 0;
Here I define an integer variable B and queue Q1.
You can create multi-threaded Code as follows:
Mythread ACC;
Thread [] MYT;
MYT = new thread [10];
Py = new mythread ();
For (INT I = 0; I <10; ++ I)
{
MYT [I] = new thread (New threadstart (Acc. dofun ));
// System. Console. writeline ("<{0}>", MYT [I]. gethashcode ());
MYT [I]. Start ();
Thread. Sleep (1000 );
}
You may be surprised to find that a class instance is used here. in the initial design, I used the mythread array. This is irrelevant to this example. When the thread needs to use different operations, it needs to use other class instances.
The complete code is as follows:
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>
/// Summary of class1.
/// </Summary>
Class classmain
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
Mythread ACC;
Thread [] MYT;
MYT = new thread [10];
Py = new mythread ();
For (INT I = 0; I <10; ++ I)
{
MYT [I] = new thread (New threadstart (Acc. dofun ));
// System. Console. writeline ("<{0}>", MYT [I]. gethashcode ());
MYT [I]. Start (); // thread running
Thread. Sleep (1000); // sleep of the main thread
}
System. Console. Read (); // wait for completion. The DOS window will not be closed immediately.
}
}
}