.NET thread synchronization (1)

zhaozj2021-02-16  30

There are many ways to process .NET thread synchronization, there are many ways to talk about the synchronization of a particular code area.

These specific code areas are important code segments in the method, and they can change the status of the object, or update another resource.

The Monitor class is used to synchronize code, which is to get a lock using the Monitor.Enter () method, then use the Monitor.exit () method to release the lock.

Examples are as follows:

Using system; using system.threading;

Namespace entexit {public class enterexit {private int result = 0; public entexit () {}

Public void noncriticalsection () {Console.writeline ("Enter Threah" thread.currentthread.getHashcode ()); for (int i = 1; i <= 5; i ) {console.writeline ("result =" result "ThreadID" thread.currentthread.gethashcode ()); thread.sleep (1000);} console.writeLine ("EXITING Threah" thread.currentthread.gethashcode ());}

Public void criticalsection () {monitor.Enter (this); console.writeline ("Enter Threah" thread.currentthread.gethashcode ()); for (int i = 1; i <= 5; i ) {console.writeline "Result =" result "ThreadID" Thread.CurrentThread.GetHashCode ()); Thread.Sleep (1000);} Console.WriteLine ( "Exiting Threah" Thread.CurrentThread.GetHashCode ()); Monitor.Exit ( THIS);

Public static void main (string [] args) {enterexit E = new enterexit (); if (args.length> 0) {thread nt1 = new thread (New ThreadStart (E.noncriticalSection); nt1.start ();

Thread NT2 = New Thread (New Threadstart (E.noncriticalSECTION); NT2.Start ();} else {thread CT1 = New Thread (New Threadstart (E.criticalSection); Ct1.Start ();

Thread CT2 = New Thread (New ThreadStart (E.criticalSection); CT2.Start ();}}}

}

operation result:

ENTER THREAH 1

Result = 0 thread1

Result = 1 thread1

Result = 2 thread1

Result = 3 thread1Result = 4 thread1

EXITING THREAD1

ENTER THREAH 2

Result = 5 thread2

Result = 6 trread2

Result = 7 trread2

Result = 8 trread2

Result = 9 thread2

EXITING THREAD2

转载请注明原文地址:https://www.9cbs.com/read-27924.html

New Post(0)