首页 > 开发 > 综合 > 正文

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

2024-07-21 02:29:41
字体:
来源:转载
供稿:网友
//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);
        }
    }
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表