Thread creation-stop

Source: Internet
Author: User

1. Create a thread
 
Thread thread = new thread (New threadstart (sortascending ));
 
2. Start the thread
 
Thread. Start ();
 
3. Terminate the thread
If you want a process to end, one way is to complete the thread's entry function execution, but in many cases this method is not enough to meet the needs of the application.
1) Abort
When the abort method is called, it will trigger threadabortexception to the thread to be terminated, and then the thread is terminated. Example:
 
Class Program
{
Static void main (string [] ARGs)
{
Thread thread = new thread (run );
Thread. Start ();
 
Thread. Sleep (1000 );
Thread. Abort ();
Console. writeline ("aborted .");
 
Console. Readline ();
}
 
Static void run ()
{
Try
{
Console. writeline ("Run executing .");
Thread. Sleep (5000 );
Console. writeline ("Run completed .");
}
Catch (threadabortexception ex)
{
Console. writeline ("caught thread abort exception .");
}
}
}
 
Running result


 
2) join
The join method blocks the calling thread until the specified Thread stops running.
 
Static void main (string [] ARGs)
{
Thread thread = new thread (run );
Thread. Start ();
 
Thread. Sleep (1000 );
Thread. Join ();
Console. writeline ("joined .");
 
Console. Readline ();
}
Www.2cto.com
Static void run ()
{
Try
{
Console. writeline ("Run executing .");
Thread. Sleep (5000 );
Console. writeline ("Run completed .");
}
Catch (threadabortexception ex)
{
Console. writeline ("caught thread abort exception .");
}
}
}
 
Running result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.