VB.NET并行与分布式编程(6)-线程与内核同步[16]
程序员文章站
2022-04-29 10:01:27
...
Imports System Imports System.Threading Imports System.Diagnostics Imports System.Diagnostics.ThreadState Module Module1 Dim myLock As New ReaderWriterLockSlim() Dim jg As Double = 300 Sub Main() Dim mythread1 As Thread Dim mythread2 As Thread Dim mythread3 As Thread '创建线程对象 mythread1 = New Thread(AddressOf mythreadrun) mythread2 = New Thread(AddressOf mythreadrun) mythread3 = New Thread(AddressOf mythreadread) mythread1.Name = "thread_1" mythread2.Name = "thread_2" mythread3.Name = "thread_3" '设置线程优先级 Console.WriteLine(Now.ToLongTimeString & "线程对象创建完毕,开始执行线程") Dim myprocess As Process = Process.GetCurrentProcess() Console.WriteLine("进程名称:" & myprocess.ProcessName) '执行线程 mythread3.Start() mythread2.Start() mythread1.Start() '等待线程完成 mythread1.Join() mythread2.Join() mythread3.Join() '线程执行完毕 Console.WriteLine(Now.ToLongTimeString & "线程执行完毕!") End Sub Public Sub mythreadrun() Dim mynum As Double Try For mynum = 1 To 100 '在3毫秒内获得写锁 If myLock.TryEnterWriteLock(3) Then jg -= mynum Console.WriteLine(Thread.CurrentThread.Name & "获得写锁==>" & Now.ToLongTimeString & "=>" & (jg + mynum) & "-" & mynum & ",计算结果为:" & jg) Thread.Sleep(3) '退出写锁 myLock.ExitWriteLock() Else Console.WriteLine(Thread.CurrentThread.Name & "==>" & Now.ToLongTimeString & "=>获得写锁失败") End If If jg < 0 Then Exit For End If Thread.Sleep(8) Next Catch Console.WriteLine(Thread.CurrentThread.Name & " " & Now.ToLongTimeString & "线程异常终止!") '终止线程 Thread.CurrentThread.Abort() Finally Console.WriteLine(Thread.CurrentThread.Name & "优先级: " & Thread.CurrentThread.Priority.ToString) Console.WriteLine(Thread.CurrentThread.Name & " " & Now.ToLongTimeString & "线程运行完毕!") End Try End Sub Public Sub mythreadread() While jg > 0 If myLock.TryEnterReadLock(2) Then Console.WriteLine(Thread.CurrentThread.Name & " 获得读锁,当前计算值为{0}", jg) Thread.Sleep(2) myLock.ExitReadLock() Else Console.WriteLine(Thread.CurrentThread.Name & " 获得读锁失败") End If Thread.Sleep(4) End While End Sub End Module
ReaderWriterLockSlim.TryEnterReadLock 方法 尝试进入读取模式锁定状态,可以选择整数超时时间。
如果调用线程已进入读取模式,则为 true;否则为 false。
效果如下:
上一篇: 1.Java语言简介
下一篇: 75.多态概述