-1

我是多线程的新手,但我不知道我的代码有什么问题:

public int k;
private void button2_Click(object sender, EventArgs e)
{
    k = 10;
    ThreadPool.SetMinThreads(2, 6);
    ThreadPool.SetMaxThreads(2, 6);
    ThreadPool.QueueUserWorkItem(aki); 
    ThreadPool.QueueUserWorkItem(aki);
}

public void aki(object ab)
{
    do
        {
           this.SetText1(textBox1.Text +
           " thread     " + Thread.CurrentThread.GetHashCode() +
           "               valu=   " + k + Environment.NewLine);
            k--;
        } while (k > 0);
        if (k < 0) Thread.CurrentThread.Abort();    
}

对于上述内容,我得到以下输出:

 thread     11               valu=   10
 thread     11               valu=   8
 thread     11               valu=   6
 thread     11               valu=   4
 thread     11               valu=   2
 thread     10               valu=   0

我期待输出 10,9,8,7,6,5,4,3,2,1,0

请指导我这有什么问题。

我试图一次运行两个线程。

该怎么办?

编辑:在rohit的回答之后,我尝试了这个,但我得到了以下输出:

 thread     11               valu=   10
 thread     12               valu=   9
 thread     12               valu=   8
 thread     11               valu=   7
 thread     11               valu=   6
 thread      6               valu=   7
 thread      6               valu=   6
 thread      6               valu=   5
 thread     13               valu=   3
 thread     14               valu=   2
 thread     14               valu=   1

在这次运行中,7 和 6 重复了两次。

4

1 回答 1

1

k这里的问题是两个线程都在你的类的同一个实例变量上工作。所以,当one thread modifies值,它gets reflected in other thread。输出将始终是不确定的。就像我得到这个输出 -

 thread     18               valu=   10
 thread     21               valu=   10
 thread     18               valu=   9
 thread     18               valu=   7
 thread     18               valu=   6
 thread     18               valu=   5
 thread     18               valu=   4
 thread     18               valu=   3
 thread     18               valu=   2
 thread     18               valu=   1
 thread     21               valu=   8

您应该在方法内使用局部变量aki-

public void aki(object ab)
{
    int k = 10; // <---- HERE
    do
        {
           this.SetText1(textBox1.Text +
                          " thread     " + Thread.CurrentThread.GetHashCode() +
                          "               valu=   " + k + Environment.NewLine);
            k--;
        } while (k >= 0); // It should be less than and equal to 0 to print 0.
        if (k < 0) Thread.CurrentThread.Abort();    
}
于 2013-07-27T08:45:01.793 回答