HelloWorld多线程C#应用 [英] HelloWorld Multithreaded C# app

查看:81
本文介绍了HelloWorld多线程C#应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例,该示例取自 http://www.albahari.com/threading/:

Consider the following example taken from http://www.albahari.com/threading/:

using System;
using System.Threading;
class ThreadTest
{
  static void Main()
  {
    Thread t = new Thread (WriteY);          // Kick off a new thread
    t.Start();                               // running WriteY()

    // Simultaneously, do something on the main thread.
    for (int i = 0; i < 1000; i++) Console.Write ("x");
  }

  static void WriteY()
  {
    for (int i = 0; i < 1000; i++) Console.Write ("y");
  }
}

如何修改代码以允许WriteY()接受字符串参数,这样我才能让一个线程传递"x"和一个传递"y"?

How do I modify the code to allow WriteY() to accept a string parameter so that I can have one thread pass "x" and one pass "y"?

推荐答案

using System;
using System.Threading;


public class ThreadTest {

    public static void Main () {

        Thread t=new Thread(WriteString);
        t.Start("y");
        Thread u=new Thread(WriteString);
        u.Start("x");

        t.Join();
        u.Join();

    }

    public static void WriteString (Object o) {

        for (Int32 i=0;i<1000;++i) Console.Write((String)o);

    }

}

这篇关于HelloWorld多线程C#应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆