Threading


'Start a Threading
 
'There're 3 Threadings in this application
Imports System.Threading
 
Public Class Form1
 
    Private trd1 As Thread
 
    Private trd2 As Thread
 
    Private p1 As Integer
 
    Private p2 As Integer
 
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
 
        '时时输出p1,p2的值
 
        Label1.Text = Str(p1)
 
        Label2.Text = Str(p2)
 
        Timer1.Stop()
 
        Timer1.Start()
   End Sub
 
 
 

一般而言,如果您想终止一个线程,您可以使用System.Threading.Thread类的Abort方法. 例如:       Dim worker As ThreadStart = New ThreadStart(AddressOf workerthreadmethod)       Dim t As Thread = New Thread(worker)       t.Start()       MessageBox.Show("Wait for a while for the thread to start.")       MessageBox.Show(t.ThreadState.ToString())       t.Abort()       MessageBox.Show(t.ThreadState.ToString())       t.Join()       MessageBox.Show(t.ThreadState.ToString())      当然,在调用Abort方法后,线程并不是立刻终止,要等线程的所有finally快中的代码完成后才会完全终止. 所以在主线程中可以用Join方法来同步,当线程还未完全终止时,t.Join()将处于等待,直到t线程完全结束后再继续执行后面的语句。   Abort方法是会导致线程跳出一个异常错误的,你需要在代码中捕获该异常。下面是一个比较完整的VB.NET线程例子:     Imports System   Imports System.Threading   Public Class MyTestApp       Public Shared Sub Main()       Dim t As New Thread(New ThreadStart(AddressOf MyThreadMethod))         'Start the thread       t.Start()       MsgBox("Are you ready to kill the thread?")         'Kill the child thread and this will cause the thread raise an exception       t.Abort()       ' Wait for the thread to exit       t.Join()       MsgBox("The secondary thread has terminated.")       End Sub     Shared Sub MyThreadMethod()       Dim i As Integer       Try           Do While True             Thread.CurrentThread.Sleep(1000)             Console.WriteLine("This is the secondary thread running.")           Loop       Catch e As ThreadAbortException           MsgBox("This thread is going to be terminated by the Abort method in the Main function")       End Try     End Sub   End Class     ************************************************************************************************

 

    Thread.Abort()方法用来永久销毁一个线程,而且将抛出ThreadAbortException异常。使终结的线程可以捕获到异常但是很难控制恢复,仅有的办法是调用Thread.ResetAbort()来取消刚才的调用,而且只有当这个异常是由于被调用线程引起的异常。因此,A线程可以正确的使用Thread.Abort()方法作用于B线程,但是B线程却不能调用Thread.ResetAbort()来取消Thread.Abort()操作。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MessageBox.Show("this is the main thread") End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Timer1.Start() trd1 = New Thread(AddressOf ThreadTask1) trd1.IsBackground = True trd1.Start() trd2 = New Thread(AddressOf ThreadTask2) trd2.IsBackground = True trd2.Start() End Sub Private Sub ThreadTask1() Dim i, j As Integer Dim f As Boolean i = 1 j = 1 p1 = 1 Do f = True For j = 2 To i - 1 If i Mod j = 0 Then f = False End If Next If f Then p1 = i End If i = i + 1 MessageBox.Show(p1) Loop End Sub Private Sub ThreadTask2() Dim i, j As Integer Dim f As Boolean i = 1 j = 1 p2 = 1 Do f = True For j = 2 To i - 1 If i Mod j = 0 Then f = False End If Next If f Then p2 = i End If i = i + 1 Loop End Sub Private Sub btnTrd1Stop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrd1Stop.Click '完全停止一个Threading trd1.Abort() End Sub Private Sub btnTrd2Stop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrd2Stop.Click trd2.Abort() End Sub End Class


### Python `threading` 库函数使用方法 #### 创建线程 可以通过继承 `Thread` 类的方式或通过回调函数的方式来创建线程。 #### 继承方式 定义一个继承自 `threading.Thread` 的子类,并重写其 `run()` 方法来实现线程逻辑。以下是具体示例: ```python import threading import time class MyThread(threading.Thread): def run(self): print(f'{self.name} start working') time.sleep(1) print(f'{self.name} end work') my_thread = MyThread() my_thread.start() # 启动线程 my_thread.join() # 等待线程结束 ``` 上述代码展示了如何通过继承 `Thread` 来创建线程[^1]。 #### 回调方式 可以直接将目标函数作为参数传入到 `Thread` 构造函数中,从而启动线程执行该函数。 ```python import threading import time def worker(): print('start working') time.sleep(1) print('end work') worker_thread = threading.Thread(target=worker) worker_thread.start() # 启动线程 worker_thread.join() # 等待线程完成 ``` 此部分说明了如何利用回调函数创建线程。 #### 参数传递 如果需要向线程的目标函数传递参数,则可以在构造 `Thread` 对象时指定 `args` 或者 `kwargs` 参数。 ```python import threading def task(arg): print(f'当前线程名称为:{threading.current_thread().name}, 参数为:{arg}') t1 = threading.Thread(target=task, args=('A',)) t2 = threading.Thread(target=task, kwargs={'arg': 'B'}) t1.start() t2.start() t1.join() t2.join() ``` 这里解释了如何在线程初始化过程中设置参数[^4]。 #### 加锁机制 当多个线程访问共享资源时可能会引发竞态条件等问题,因此需要用到同步原语如互斥锁 (`Lock`) 进行保护。 ```python import threading lock = threading.Lock() counter = 0 def increment(): global counter lock.acquire() # 获取锁 try: counter += 1 finally: lock.release() # 释放锁 threads = [threading.Thread(target=increment) for _ in range(10)] for t in threads: t.start() for t in threads: t.join() print(counter) ``` 这部分描述了如何运用 `threading.Lock` 防止数据竞争。 #### 原子操作 对于某些简单场景下的并发控制需求,还可以考虑采用原子变量等方式简化处理流程,在支持相应特性的版本里可选用更高级别的抽象工具替代传统手动加解锁手段。 注意:Python 并未内置真正的 `atomic` 支持,需借助第三方扩展包或是基于已有组件模拟实现近似效果;而官方文档推荐尽可能依赖队列等更高层次通信设施减少直接干预底层细节带来的复杂度风险[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值