CSharp基础 专题
专题目录
您的位置:csharp > CSharp基础 专题 > C#线程实例
C#线程实例
作者:--    发布时间:2019-11-20

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

using system;
using system.threading;
public class mythread
{
    public static void thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            console.writeline("thread1: "+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();
    }
}

上述程序的输出可以是任何东西,因为线程之间有上下文切换。在我运行上面示例时输出以下结果 -

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

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

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

using system;
using system.threading;

public class mythread
{
    private string name;

    public mythread(string name)
    {
        this.name = name;
    }
    public void thread1()
    {
        for (int i = 0; i < 10; i++)
        {
            console.writeline(this.name+": "+i);
        }
    }
}

public class threadexample
{
    public static void main()
    {
        mythread mt = new mythread("thread1");
        mythread mt2 = new mythread("thread2");
        thread t1 = new thread(new threadstart(mt.thread1));
        thread t2 = new thread(new threadstart(mt2.thread1));
        t1.start();
        t2.start();
    }
}

这个程序的输出可以是任何顺序,因为线程之间有上下文切换,所以每次执行的结果都不太一样。输出结果如下所示 -

thread1: 0
thread1: 1
thread2: 0
thread2: 1
thread2: 2
thread2: 3
thread2: 4
thread2: 5
thread2: 6
thread2: 7
thread2: 8
thread2: 9
thread1: 2
thread1: 3
thread1: 4
thread1: 5
thread1: 6
thread1: 7
thread1: 8
thread1: 9

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

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

using system;
using system.threading;

public class mythread
{
    public static void method1()
    {
        for (int i = 0; i < 5; i++)
        {
            console.writeline("this is method1 :" + i);
        }
    }
    public static void method2()
    {
        for (int i = 0; i < 5; i++)
        {
            console.writeline("this is method2 :"+i);
        }

    }
}
public class threadexample
{
    public static void main()
    {
        thread t1 = new thread(new threadstart(mythread.method1));
        thread t2 = new thread(new threadstart(mythread.method2));
        t1.start();
        t2.start();
    }
}

这个程序的输出可以是任何顺序,因为线程之间有上下文切换,所以每次执行的结果都不太一样。输出结果如下所示 -

this is method1 :0
this is method1 :1
this is method2 :0
this is method2 :1
this is method2 :2
this is method2 :3
this is method2 :4
this is method1 :2
this is method1 :3
this is method1 :4

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册