Java 5 and later provide excellent concurrent libraries util. concurrent,. net lack similar functions. As the hardware system has changed and the multi-core era is approaching, the lack of concurrent class libraries in. NET is obviously out of date. One method is to port java's util. concurrent to C.
The util. concurrent package in java provides LockSupport class. Many key implementations of util. concurrent package need to call LockSupport. To Migrate java's util. concurrent package to C #, The LockSupport class migration is inevitable.
In java, the LockSupport class has the following methods: Public static void park (Object blocker ){
Thread t = Thread. currentThread ();
SetBlocker (t, blocker );
Unsafe. park (false, 0L );
SetBlocker (t, null );
}
When a thread calls LockSupport. park, the thread stops downloading, similar to Object. wait, or System. Threading. Monitor. Wait in. NET. But the problem is that the Object in java. wait and. NET. wait requires a waitObject. This problem has plagued me. For this reason, JDK 6 implements the source code. The solution found at the end is very simple, you do not need to know the underlying implementation source code of JDK.
Public class LockSupport
{
Private static LocalDataStoreSlot slot = Thread. GetNamedDataSlot ("LockSupport. Park ");
Public static void Park (Object blocker)
{
Thread thread = Thread. CurrentThread;
Thread. SetData (slot, blocker );
Lock (thread)
{
Monitor. Wait (thread );
}
}
Public static void Unpark (Thread thread)
{
If (thread = null) return;
Lock (thread)
{
Monitor. Pulse (thread );
}
}
}
The slot is unnecessary, but you can see in the LockSupport code of JDK util. concurrent that using slot (java ThreadLocal) can be used for tracking and debugging.