编程|多线程
//HelloWordThread.cs
//------------------------
using System;using System.Threading;public class Test{ static void Main() { ThreadStart job = new ThreadStart(ThreadJob); Thread thread = new Thread(job); thread.Start(); for (int i=0; i < 5; i++) { Console.WriteLine ("Main thread: {0}", i); Thread.Sleep(1000); } } static void ThreadJob() { for (int i=0; i < 10; i++) { Console.WriteLine ("Other thread: {0}", i); Thread.Sleep(500); } }}
结果:
Main thread: 0Other thread: 0Other thread: 1Main thread: 1Other thread: 2Other thread: 3Main thread: 2Other thread: 4Other thread: 5Main thread: 3Other thread: 6Other thread: 7Main thread: 4Other thread: 8Other thread: 9 |
//UsingDelegate.cs
------------------------------------
using System;
using System.Threading;
public class Test
{
static void Main()
{
Counter foo = new Counter();
ThreadStart job = new ThreadStart(foo.Count);
Thread thread = new Thread(job);
thread.Start();
for (int i=0; i < 5; i++)
{
Console.WriteLine ("Main thread: {0}", i);
Thread.Sleep(1000);
}
}
}
public class Counter
{
public void Count()
{
for (int i=0; i < 10; i++) { Console.WriteLine ("Other thread: {0}", i);
Thread.Sleep(500);
}
}
}