C#多线程的几种实现方法详解编程语言

1.最简单的多线程

using System; 
using System.Threading; 
 
namespace ThreadTest1 
{ 
    public class SimpleThread 
    { 
        public void Run() 
        { 
            Thread t1 = new Thread(new ThreadStart(this.ThreadFunc)); 
            Thread t2 = new Thread(new ThreadStart(this.ThreadFunc)); 
            t1.Start(); 
            Thread.Sleep(1000); 
            t2.Start(); 
        } 
 
        private void ThreadFunc() 
        { 
            for (int i = 0; i < 100; i++) 
            { 
                Console.WriteLine(i); 
                Thread.Sleep(100); 
            } 
        } 
    } 
} 
 

2.可以传参数的多线程

using System; 
using System.Threading; 
 
namespace ThreadTest1 
{ 
    class ThreadWithPara 
    { 
        public void Run() 
        { 
            Thread t1 = new Thread(ThreadFunc); 
            Thread t2 = new Thread(new ParameterizedThreadStart(ThreadFunc)); 
            t1.Start("t1"); 
            Thread.Sleep(1000); 
            t2.Start("t2"); 
        } 
 
        private void ThreadFunc(object obj) 
        { 
            for (int i = 0; i < 100; i++) 
            { 
                Console.WriteLine(i + obj.ToString()); 
                Thread.Sleep(100); 
            } 
        } 
    } 
} 
 

3.自定义类的多线程

using System; 
using System.Threading; 
 
namespace ThreadTest1 
{ 
    class MyThreadClass 
    { 
        private string data; 
 
        public MyThreadClass(string data) 
        { 
            this.data = data; 
        } 
 
        public void ThreadMain() 
        { 
            Console.WriteLine("Running in a thread,data: {0}", data); 
        } 
    } 
 
    class MainClass 
    { 
        public void Run() 
        { 
            MyThreadClass mtc = new MyThreadClass("thread1"); 
            Thread thread = new Thread(mtc.ThreadMain); 
            thread.Start(); 
        } 
    } 
} 
 

4. 匿名方法实现的多线程

using System; 
using System.Threading; 
 
namespace ThreadTest1 
{ 
    public class AnonymousThread 
    { 
        public void Run() 
        { 
            Thread t1 = new Thread(() => ThreadFunc("thread-1")); 
            t1.Start(); 
        } 
 
        private void ThreadFunc(string obj) 
        { 
            for (int i = 0; i < 100; i++) 
            { 
                Console.WriteLine(i + obj.ToString()); 
                Thread.Sleep(100); 
            } 
        } 
    } 
} 
 

5.参考

C# 给多线程传参的三种方式

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/8901.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论