有趣的多线程编程(1)——一个简单的例子

王朝other·作者佚名  2006-02-04
窄屏简体版  字體: |||超大  

//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: 0

Other thread: 0

Other thread: 1

Main thread: 1

Other thread: 2

Other thread: 3

Main thread: 2

Other thread: 4

Other thread: 5

Main thread: 3

Other thread: 6

Other thread: 7

Main thread: 4

Other thread: 8

Other 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);

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航