imports System
imports System.Threading
public class AClass
public sub Method1()
Dim i as integer
For i = 1 to 100
Console.Writeline("這是類AClass方法method1的內(nèi)容",i)
next
end sub
public sub Method2()
Dim i as integer
For i = 1 to 100
Console.Writeline("這是類AClass方法method2的內(nèi)容",i)
next
end sub
end class
public class ThreadTest
public shared sub Main()
dim obj as new aclass
dim th1,th2 as thread
th1=new Thread(new ThreadStart(addressof obj.method1))
th1.start
th2=new Thread(new ThreadStart(addressof obj.method2))
th2.start
dim i as integer
For i= 1 to 100
Console.WriteLine("Main方法里的內(nèi)容",i)
Next
end sub
end class
現(xiàn)在,來讓我們剖析一下上面的例子:
1.我們創(chuàng)建了我們自己的類AClass,并創(chuàng)建了兩個方法:Method1和Method2。
2.這兩個方法很簡單,只有一個For循環(huán),向輸出設(shè)備輸出一些信息。
3.我們還定義了另外一個類ThreadTest來使用上面創(chuàng)建的類AClass。
4.在Main()方法中,我們創(chuàng)建了類Thread的實例。
5.類Thread可以在System.Threading名字空間里得到,它定義了處理線程的屬性和方法。 6.在類Thread的構(gòu)造器中,我們使用了類ThreadStart,類ThreadStart是一個代表,標(biāo)志著當(dāng)一個線程開始時就開始執(zhí)行定義的方法。
7.為了執(zhí)行定義的方法,我們實際調(diào)用的是線程的Start()方法。
8用VBC來編譯上面的程序: vbc /out:threadtest.exe threadtest.vb
9.運行編譯后的程序,我們將會看到我們定義的兩個方法和main()方法的混合輸出,這就說明每一個方法都在自己的線程下運行。
10.除了上面的方法,線程還有下面常用的方法:
Stop():停止線程的運行。
Suspend():暫停線程的運行。
Resume():繼續(xù)線程的運行。
Sleep():停止線程一段時間(單位為毫秒)。
上面只是VB.NET多線程的一個簡單的例子,希望對大家有所啟發(fā)!
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。