现在的位置: 首页 > 综合 > 正文

模拟 .net framework 4.0 的 parallel

2013年01月12日 ⁄ 综合 ⁄ 共 706字 ⁄ 字号 评论关闭

1. .net framework 3.5 下 简单模仿:

using System;
using System.Threading;

public class Test5
{
    public static void Main(String[] args)
    {
        //模拟 4.0 的 Parallel
        Thread.CurrentThread.Name = "主线程";
        Console.WriteLine(string.Format("当前线程:{0} 开始", Thread.CurrentThread.Name));

        Thread[] threadArr = new Thread[3];

        for (int i=1;i<=threadArr.Length;i++) 
        {
            threadArr[i-1] = new Thread(ExecuteThread);
            threadArr[i-1].Name = i.ToString();
            threadArr[i-1].Start();
            //threadArr[i-1].Join();    //写在此处会让3个线程顺序执行而失去意义
        }

        foreach (Thread th in threadArr)
            th.Join();

        Console.WriteLine(string.Format("当前线程:{0} 结束", Thread.CurrentThread.Name));
        Console.Read();
    }

    public static void ExecuteThread() 
    {
        for (int i = 1; i <= 10; i++) 
        {
            Console.WriteLine(string.Format("当前线程名:{0}, 输出值:{1}", Thread.CurrentThread.Name, i));
        }
    }
}

抱歉!评论已关闭.