| || |
Join Date: Aug 2008
Creating and executing a thread.
Thread synchronization: To allow threads to cooperate and compete for resources, it is necessary to provide mechanisms for synchronization and communication.
Interaction between threads: The program begins by creating an object of type Alpha (oAlpha) and a thread (oThread) that references the Beta method of the Alpha class. The thread is then started. The IsAlive property of the thread allows the program to wait until the thread is initialized (created, allocated, and so on). The main thread is accessed through Thread, and the Sleep method tells the thread to give up its time slice and stop executing for a certain amount of milliseconds. The oThread is then stopped and joined. Joining a thread makes the main thread wait for it to die or for a specified time to expire (for more details, see Thread.Join Method). Finally, the program attempts to restart oThread, but fails because a thread cannot be restarted after it is stopped (aborted).
public class Alpha
// This method that will be called when the thread is started
public void Beta()
Console.WriteLine("Alpha.Beta is running in its own thread.");
public class Simple
public static int Main()
Console.WriteLine("Thread Start/Stop/Join Sample");
Alpha oAlpha = new Alpha();
// Create the thread object, passing in the Alpha.Beta method
// via a ThreadStart delegate. This does not start the thread.
Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
// Start the thread
// Spin for a while waiting for the started thread to become
// Put the Main thread to sleep for 1 millisecond to allow oThread
// to do some work:
// Request that oThread be stopped
// Wait until oThread finishes. Join also has overloads
// that take a millisecond interval or a TimeSpan object.
Console.WriteLine("Alpha.Beta has finished");
Console.WriteLine("Try to restart the Alpha.Beta thread");
Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
Console.WriteLine("Expected since aborted threads cannot be restarted.");