C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# Threading Example: static method 线程示例:静态方法

我们可以在线程的执行上调用静态和非静态方法。要调用静态和非静态方法,需要在 ThreadStart 类的构造函数中传递方法名。对于静态方法,我们不需要创建类的实例。你可以通过类名来引用它。

例子 (Example)

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();  
    }  
}

输出:

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

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

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

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

例子 (Example)

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# 线程示例:在每个线程上执行不同的任务

让我们看一个例子,我们在每个线程上执行不同的方法。

例子 (Example)

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();  
    }  
}

Output:

task one
task two


  • 使用社交账号登录,本站支持
全部评论(0)