多线程学习(一)
程序员文章站
2022-09-27 22:23:31
线程的基本操作线程的基本操作包括:创建线程、暂停线程、线程等待、终止线程。 工作原理在Main方法外定义了方法FristPrintNumbers、SecondPrintNumbers,该方法会被主程序和向创建的两个线程Thread1、Thread2使用。创建完成线程后,使用Start方法启动线程,使 ......
线程的基本操作
线程的基本操作包括:创建线程、暂停线程、线程等待、终止线程。
1 /*----------------------------------------------------------------------- 2 written by helio, 2019 3 threadsample1 4 -----------------------------------------------------------------------*/ 5 using system; 6 using system.threading; 7 8 namespace threadsample 9 { 10 class program 11 { 12 static void firstprintnumbsers() 13 { 14 console.writeline("{0} starting..", thread.currentthread.name); 15 for (int i = 1; i <= 10; i++) 16 { 17 console.writeline(i); 18 thread.sleep(timespan.frommilliseconds(100)); 19 } 20 } 21 22 static void secondprintnumbers() 23 { 24 console.writeline("{0} starting...", thread.currentthread.name); 25 for (int i = 1; i <= 10; i++) 26 { 27 console.writeline(i); 28 thread.sleep(timespan.frommilliseconds(100)); 29 } 30 } 31 static void main(string[] args) 32 { 33 thread t1 = new thread(firstprintnumbsers); 34 thread t2 = new thread(secondprintnumbers); 35 t1.name = "thread1"; 36 t2.name = "thread2"; 37 t1.start(); 38 t2.start(); 39 t1.join(); 40 t2.join(); 41 42 thread.currentthread.name = "mainthread"; 43 firstprintnumbsers(); 44 console.readkey(); 45 } 46 } 47 }
工作原理
在main方法外定义了方法fristprintnumbers、secondprintnumbers,该方法会被主程序和向创建的两个线程thread1、thread2使用。创建完成线程后,使用start方法启动线程,使用join方法值线程执行完成后继续执行主线程或者该线程下面的线程。
前台线程和后台线程
1 ``` 2 /*----------------------------------------------------------------------- 3 written by helio, 2019 4 threadsample2 5 -----------------------------------------------------------------------*/ 6 using system; 7 using system.threading; 8 9 namespace threadsample 10 { 11 class program 12 { 13 static void main(string[] args) 14 { 15 var sampleforeground = new threadsample(10); 16 var samplebackground = new threadsample(20); 17 18 var threadone = new thread(sampleforeground.countnumbers); 19 threadone.name = "foregourndthread"; 20 var threadtwo = new thread(samplebackground.countnumbers); 21 threadtwo.name = "backgroundthread"; 22 threadtwo.isbackground = true; 23 24 threadone.start(); 25 threadtwo.start(); 26 } 27 28 class threadsample 29 { 30 private readonly int m_iteration; 31 32 public threadsample(int iteration) 33 { 34 m_iteration = iteration; 35 } 36 37 public void countnumbers() 38 { 39 for (int i = 0; i < m_iteration; i++) 40 { 41 thread.sleep(timespan.fromseconds(0.5)); 42 console.writeline("{0} prints {1}", 43 thread.currentthread.name, i); 44 } 45 } 46 } 47 } 48 } 49 ```
工作原理
当主程序启动时定义了两个不同的线程。默认情况下,显示创建的线程是前台线程。通过手动设置thradtow对象的isbackkgournd来创建一个后台线程。<br/>
当一个程序中的前台线程完成工作后,程序就会关闭,即使还有未完成工作的后台线程。所以在上述程序中,前台线程thread1完成工作后程序就会别关闭。
可访问我的个人博客