Multi-thread knowledge and multi-thread knowledge

Source: Internet
Author: User

Multi-thread knowledge and multi-thread knowledge

I,Process/thread

Process: An independent unit for the system to allocate and schedule resources. (Save resources)

Thread: The basic unit for CPU scheduling and scheduling. (Execution)

A process can have multiple threads. A thread can share all the resources of a process with other threads of the same process.

Scenario: supermarkets.

/// <Summary>
/// Single thread
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button#click (object sender, EventArgs e)
{
// Int sum = 0;
// For (int I = 1; I <999999999; I ++)
//{
// Sum + = I;
//}
// MessageBox. Show (sum. ToString (); // other operations can be performed only after execution.
}

/// <Summary>
/// Multithreading
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void button3_Click (object sender, EventArgs e)
{
Thread thread = new Thread (TestThread );
Thread. IsBackground = true; // set it to a background thread
Thread. Start ();
}

/// <Summary>
/// Prepare the thread to call
/// </Summary>
Private void TestThread ()
{
Int sum = 0;
For (int I = 1; I <999999999; I ++)
{
Sum + = I;
}
MessageBox. Show (sum. ToString (); // after execution, other operations can be performed.
}


1 /// <summary> 2 /// single thread 3 /// </summary> 4 /// <param name = "sender"> </param> 5 // /<param name = "e"> </param> 6 private void button#click (object sender, eventArgs e) 7 {8 // int sum = 0; 9 // for (int I = 1; I <999999999; I ++) 10 // {11 // sum + = I; 12 //} 13 // MessageBox. show (sum. toString (); // after execution, to perform other operations 14} 15 16 /// <summary> 17 // multithreading 18 /// </summary> 19 /// <param name = "sender"> </param> 20 // <param name = "e"> </param> 21 private void button3_Click (object sender, eventArgs e) 22 {23 Thread thread = new Thread (TestThread); 24 thread. isBackground = true; // set it to background thread 25. start (); 26} 27 28 /// <summary> 29 // prepare for the thread to call 30 /// </summary> 31 private void TestThread () 32 {33 int sum = 0; 34 for (int I = 1; I <999999999; I ++) 35 {36 sum + = I; 37} 38 MessageBox. show (sum. toString (); // other operations can be performed 39}

II,Foreground thread/background thread

1. The default thread in the process isMain thread(UI thread ).

2. By default, all threads are front-end threads (the program exits after all threads are executed). For example, to set them to backend threads (after the window is closed, the program ends ), set thead. isBackground = true.

Iii. Thread re-entry and Solution

1. In demo2, textbox is created by the ui thread, so the created thread cannot be called. Therefore, the program reports an error at the beginning. You only need to disable the cross-thread access check of the control.

2. Multiple Threads access the same resource, which may cause non-synchronization. This is called thread re-import. UseLock (this)Processing. this indicates the current object. Only one thread can be executed before another thread can be executed.

Public demo2 ()
{
InitializeComponent ();
TextBox. checkforillegalcrossthreadcils = false; // close the cross-thread access check of the control.
}
Thread thread;
Private void button#click (object sender, EventArgs e)
{
Thread = new Thread (CountNum );
Thread. IsBackground = true;
Thread. Start ();

// Thread thread1 = new Thread (CountNum );
// Thread1.IsBackground = true;
// Thread1.Start ();
}
Private void CountNum ()
{
Lock (this) // this indicates the current object. Only one thread can execute other threads.
{
For (int I = 0; I <10000; I ++)
{
Int num = Convert. ToInt32 (textBox1.Text. Trim ());
Num ++;
// Thread. Sleep (1000 );

// If (num = 5000)
//{
// Thread. Abort ();
//}
TextBox1.Text = num. ToString ();
}
}
}

4. Thread Scheduling

1. Non-preemptible scheduling: A thread will not be forcibly paused by the operating system during running, and the operation right will be handed over after running. Once a program dies, the entire computer can only be restarted.

2. preemptible scheduling: Each thread has only a very short running time (in windows kernel mode, this time will not exceed 20 ms). When the time is used up, the thread will be forcibly suspended, save the context and give the cpu running permission to the next thread.

5. common attributes of threads

1. Abort method: forcibly stop the thread.

2. Sleep (MS): The number of milliseconds to pause the current thread, static method

6. Lottery Program

Public demo3 () {InitializeComponent (); Label. checkforillegalcrossthreadcils = false;} Thread thead; private void button#click (object sender, EventArgs e) {if (button1.Text = "") {thead = new Thread (RunLuck); thead. isBackground = true; thead. start (); button1.Text = "Stop lottery";} else {thead. abort (); button1.Text = "" ;}} Random r = new Random (); public void RunLuck () {while (true) {Th Read. Sleep (100); foreach (Control c in groupBox1.Controls) {Label lab = c as Label; if (lab! = Null) {lab. Text = r. Next (0, 10). ToString ();}}}}

  

7. The thread calls a method with Parameters

Public demo4 ()
{
InitializeComponent ();
}
Private void button#click (object sender, EventArgs e)
{
ParameterizedThreadStart s = new ParameterizedThreadStart (TestThreadParsms );
Thread t = new Thread (s );
T. IsBackground = true;
T. Start ("Hello ");
}
Public void TestThreadParsms (object obj) // only object type parameters can be passed here. This parameter is consistent with the delegate parameter. to upload multiple parameters, create an array.
{
MessageBox. Show (obj. ToString ());
}


1 public demo4 () 2 {3 InitializeComponent (); 4} 5 private void button1_Click (object sender, EventArgs e) 6 {7 ParameterizedThreadStart s = new ParameterizedThreadStart (TestThreadParsms ); 8 Thread t = new Thread (s); 9 t. isBackground = true; 10 t. start (""); 11} 12 public void TestThreadParsms (object obj) // only object type parameters can be passed here, which is consistent with the delegate parameters. to upload multiple parameters, you can create an array of 13 {14 MessageBox. show (obj. toString (); 15}

Related Article

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.