-2

我的线程有问题,这是一个代码:

class myThread
{
    public int _start, _finish;
    string[] new_array = new string[10];
    public static string[] existed_array = new string[20];    
    public myThread(string name, int start, int finish)
    {
        _start = start;
        _finish = finish;
        Thread thread = new Thread(this.Get);
        thread.Name = name;
        thread.Start();//передача параметра в поток
     }

    void Get()
    {
        for (int ii = _start; ii < _finish; ii++)
        {
           // i put data in existed array in Main()
           // new array is just an array where i want to put existed data
           new_array[ii] = existed_array[ii];
           // but in output new_array[0]=null; new_array[1]=value
        }
    }
}

void Main ()
{
    // For example
    myThread.existed_array = {1, 2 , 3, ...}

    myThread t1 = new myThread("Thread 1", 0, 1);
    myThread t2 = new myThread("Thread 2", 1, 2);
}

线程使用不同的参数运行 Get(),但在输出中只有第二个线程的参数。正如我从逐步程序中看到的那样,Get 函数中的每一行都运行了 2 次,所以这就是重点,我该如何解决这个问题?

4

1 回答 1

1

如果我理解正确,您的代码将按预期运行。

在您的评论中,您声称“但在输出中 new_array[0]=null; new_array[0]=value”。我对此的解释是,在您的第二个线程中new_array[0] = null,以及在您的第一个线程中,new_array[0] = <some value>

根据您的代码,new_array它是一个非静态变量,这意味着它不跨线程共享。

考虑到您提供给第二个线程的参数,它永远不会触及数组中的第 0 个。您已将起始值设置为 1,因此ii从 1 开始。这意味着您从未设置new_array[0]任何内容,因此默认为null.

于 2012-09-09T07:59:49.747 回答