C # multithreading I
Using system;
Using system. Threading;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace a0300_thread.sample
{
/// <Summary>
/// The simplest example of a thread
///
/// The thread execution method is defined as a static method.
/// </Summary>
Class staticthreadsample
{
/// <Summary>
/// Simple thread execution method.
///
/// This method is static
/// </Summary>
Public static void threadfunc ()
{
// Indicates that the thread stops running.
Boolean done = false;
// Counter
Int count = 0;
While (! Done)
{
// Sleep for 1 second.
Thread. Sleep (1000 );
// Counter increments
Count ++;
// Output.
Console. WriteLine ("[Static] execution times: {0}", count );
}
}
/// <Summary>
/// Code of the startup thread.
/// </Summary>
Public static void StartThread ()
{
ThreadStart ts = new ThreadStart (ThreadFunc );
Thread t = new Thread (ts );
// Start.
T. Start ();
}
}
}
Using system;
Using system. Threading;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace a0300_thread.sample
{
/// <Summary>
/// The simplest example of a thread
///
/// The thread execution method is defined as a normal method.
/// </Summary>
Class threadsample
{
/// <Summary>
/// Simple thread execution method.
///
/// This method is not static
/// </Summary>
Public void threadfunc ()
{
// Indicates that the thread stops running.
Boolean done = false;
// Counter
Int COUNT = 0;
While (! Done)
{
// Sleep for 2 seconds.
Thread. Sleep (2000 );
// Counter increments
Count ++;
// Output.
Console. writeline ("[Normal] execution times: {0}", count );
}
}
/// <Summary>
/// Code of the startup thread.
///
///
/// Note: the difference between a static method and a common method in multithreading is that a common method needs to create an instance of the class.
/// </Summary>
Public static void StartThread ()
{
ThreadSample sample = new ThreadSample ();
ThreadStart ts = new ThreadStart (sample. ThreadFunc );
Thread t = new Thread (ts );
// Start.
T. Start ();
}
}
}
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using A0300_Thread.Sample;
Namespace A0300_Thread
{
Class Program
{
Static void Main (string [] args)
{
// Static thread method.
Staticthreadsample. startthread ();
// Common thread method.
Threadsample. startthread ();
Console. writeline ("press Ctrl + C to end the operation! ");
}
}
}