在执行线程时可以调用静态和非静态方法。要调用静态和非静态方法,需要在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
上一篇:
C#主线程
下一篇:
C#线程实例:Sleep()方法