C# - 线程示例

C# - 线程示例 首页 / C#入门教程 / C# - 线程示例

无涯教程可以在线程的执行上调用Static静态和非Static静态方法。要调用静态和非静态方法,需要在ThreadStart类的构造函数中传入方法名。对于Static静态方法,不需要创建类的实例。您可以通过类的名称来引用它。

using System;  
using System.Threading;  
public class MyThread  
{  
    public static void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));  
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread1));  
        t1.Start();  
        t2.Start();  
    }  
}  

输出:

以上程序的输出可以是任何内容,因为线程之间存在上下文切换。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-threading-example.html

来源:LearnFk无涯教程网

0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9

C#线程化示例:非Static静态方法

对于非Static静态方法,需要创建类的实例,以便在ThreadStart类的构造函数中引用。

using System;  
using System.Threading;  
public class MyThread  
{  
    public void Thread1()  
    {  
        for (int i = 0; i < 10; i++)  
        {  
            Console.WriteLine(i);  
        }  
    }  
}  
public class ThreadExample  
{  
    public static void Main()  
    {  
        MyThread mt = new MyThread();  
        Thread t1 = new Thread(new ThreadStart(mt.Thread1));  
        Thread t2 = new Thread(new ThreadStart(mt.Thread1));  
        t1.Start();  
        t2.Start();  
    }  
}  

输出:

与上面的程序输出一样,该程序的输出可以是任何内容,因为线程之间存在上下文切换。

0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
6
7
8
9

C#线程化示例:在每个线程上执行不同的任务

让无涯教程看一个示例,其中在每个线程上执行不同的方法。

无涯教程网

using System;
using System.Threading;

public class MyThread
{
    public static void Thread1()
    {
        Console.WriteLine("task one");
    }
    public static void Thread2()
    {
        Console.WriteLine("task two");
    }
}
public class ThreadExample
{
    public static void Main()
    {
        Thread t1 = new Thread(new ThreadStart(MyThread.Thread1));
        Thread t2 = new Thread(new ThreadStart(MyThread.Thread2));
        t1.Start();
        t2.Start();
    }
}

输出:

task one
task two

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据分析实战45讲 -〔陈旸〕

深入拆解Tomcat & Jetty -〔李号双〕

分布式技术原理与算法解析 -〔聂鹏程〕

JavaScript核心原理解析 -〔周爱民〕

代码之丑 -〔郑晔〕

体验设计案例课 -〔炒炒〕

性能优化高手课 -〔尉刚强〕

中间件核心技术与实战 -〔丁威〕

运维监控系统实战笔记 -〔秦晓辉〕

好记忆不如烂笔头。留下您的足迹吧 :)