您的位置:首页 > 编程语言

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

2006-02-19 12:51 369 查看
//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);
        }
    }
}

结果:
[code]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
[/code]
//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);
}
}
}

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=589224
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: