Next, we will create a thread. When using the Thread class to create a thread, we only need to provide the thread entry. Thread entry enabling Program Know what to do with this thread. in C #, the thread entry is provided through the threadstart proxy (delegate). You can understand threadstart as a function pointer, point to the function to be executed by the thread. after the start () method, the thread starts to execute the Functions Represented or pointed to by threadstart.
Open your vs.net and create a console application.CodeIt will make you feel the pleasure of completely controlling a thread!
| // Threadtest. CS Using system; Using system. Threading; Namespace threadtest { Public Class Alpha { Public void beta () { While (true) { 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 (); file: // create a thread to execute beta () of the Alpha Class () method thread othread = new thread (New threadstart (oalpha. beta); othread. start (); while (! Othread. isalive); thread. sleep (1); othread. abort (); othread. join (); console. writeline (); console. writeline ("Alpha. beta has finished "); try {< br> console. writeline ("try to restart the Alpha. beta thread "); othread. start (); }< br> catch (threadstateexception) {< br> console. write ("threadstateexception trying to restart Alpha. beta. "); console. writeline ("expected since aborted threads cannot be restarted. "); console. readline (); }< br> return 0; }< BR >} |
This program contains two classes: Alpha and simple. when creating the thread othread, we use the pointer to Alpha. the threadstart proxy (delegate) object is initialized in the beta () method. When the created thread othread calls othread. when the START () method is started, the actual program running is Alpha. beta () method:
Alpha oalpha = new alpha (); Thread othread = new thread (New threadstart (oalpha. Beta )); Othread. Start (); |
Then in the while loop of the main () function, we use the static method thread. Sleep () to stop the main thread for 1 ms. During this time, the CPU turns to the execution thread othread. Then we try to use the thread. Abort () method to terminate the thread othread. Pay attention to the following othread. Join (), thread. Join () method to wait for the main thread until the othread thread ends. You can specify an int-type parameter for the thread. Join () method as the maximum waiting time. Later, we tried to use the thread. Start () method to restart the thread othread, but obviously the consequence of the abort () method is that the thread cannot be recovered, so the program will throw a threadstateexception.
The final result of the program will be as follows: