C#多线程的简单例子
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; //using System.Threading.Tasks; using System.IO; using System.Collections; namespace ConsoleApplication2 { class program { static void Main(string[] args) { Console.WriteLine("开始一个新的线程,名为次线程"); Thread t = new Thread(new ThreadStart(ThreadProc)); t.Start(); for (int i = 0; i < 4; i++) { Console.WriteLine("主线程:" + i); Thread.Sleep(1000); } Console.WriteLine("调用Join函数等待次线程结束"); //当次线程执行完毕后,Join阻塞调用线程,直到某个线程终止为止,本例为次线程 t.Join(); Console.WriteLine("线程执行完毕"); } public static void ThreadProc() { for (int i = 0; i < 10; i++) { Console.WriteLine("ThreadPorc:{0}", i); Thread.Sleep(1000);//将当前进程阻塞指定的毫秒数 } } } }
static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(Thread1)); Thread t2 = new Thread(new ThreadStart(Thread2)); t1.Priority = ThreadPriority.BelowNormal ; t2.Priority = ThreadPriority.Lowest ; t1.Start(); t2.Start(); } public static void Thread1() { for (int i = 1; i < 1000; i++) {//每运行一个循环就写一个“1” dosth(); Console.Write("1"); } } public static void Thread2() { for (int i = 0; i < 1000; i++) {//每运行一个循环就写一个“2” dosth(); Console.Write("2"); } } public static void dosth() {//用来模拟复杂运算 for (int j = 0; j < 10000000; j++) { int a=15; a = a*a*a*a; } }