2012-01-04 171 views
1

考虑从http://www.albahari.com/threading/采取了以下例子:的HelloWorld多线程C#应用程序

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”?

回答

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

    } 

} 
+0

为什么您的方法需要JOIN方法,而不是使用Lamba方法? – ChadD 2012-01-04 02:44:47

+0

这不是“需要”,我只是希望在退出“Main”之前确保我的线程已经退出。 – 2012-01-04 02:54:30

+0

@RobertAllanHenniganLeahy我对你的回复感兴趣,只是用它来测试它,但我有一个如下问题 - 我怎么能通过多个参数?说我想通过循环计数,所以它不固定在1000.谢谢 – harag 2012-01-04 14:24:47

3

尝试使用lambda表达式:

class ThreadTest 
{ 
    static void Main() 
    { 
    Thread t = new Thread (() => Write("y"));   // Kick off a new thread 
    t.Start();        // running WriteY() 

    // Simultaneously, do something on the main thread. 
    Write("x"); 
    } 

    static void Write(string input) 
    { 
    for (int i = 0; i < 1000; i++) Console.Write (input); 
    } 
} 
1

基本上你需要实现三个转变。

//1. change how the thread is started 
t.Start("y");        // running WriteY() 

//2.change how the signature of the method 
static void WriteY(object data) 
    { 
    //3. use the data parameter 
    for (int i = 0; i &lt; 1000; i++) Console.Write ((string) data); 
    } 
}