我正在使用以下 .NET 代码
Class MonitorSample
Shared Sub RunMonitor()
Dim o As New Object()
For i As Integer = 0 To 99
ThreadPool.QueueUserWorkItem(Function()
Try
Monitor.Enter(o)
Console.WriteLine("Thread {0} acquired lock...working", Thread.CurrentThread.ManagedThreadId)
Console.WriteLine("Thread {0} performing some I/O operation so yielding the lock temporarily...", Thread.CurrentThread.ManagedThreadId)
Monitor.PulseAll(o)
Monitor.Wait(o)
Console.WriteLine("Thread {0} reacquired lock", Thread.CurrentThread.ManagedThreadId)
Finally
Console.WriteLine("Thread {0} released lock", Thread.CurrentThread.ManagedThreadId)
Monitor.PulseAll(o)
Monitor.Exit(o)
End Try
Return Nothing
End Function
)
Next
Console.ReadLine()
End Sub
Shared Sub Main()
Dim stopwatch As New Stopwatch()
stopwatch.Start()
RunMonitor()
stopwatch.Stop()
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed)
End Sub
End Class
在 main 方法中,这是计算线程消耗时间的正确方法,或者我们应该以其他方式计算。
实际上,打印时间消耗的步骤首先打印,而线程稍后执行。