簡體   English   中英

為什么在產生線程時會出現意外輸出?

[英]Why am I getting unexpected output when spawning threads?

我試圖產生一定數量的線程。 但是當我向函數傳遞參數時,輸出是隨機的。 它多次選擇變量'i'的某些值並忽略一些。 我是C#的新手。 請解釋我做錯了什么。

using System;
using System.Threading;

public class first
{
     public static void tone(int i)
{
        Console.WriteLine("Hi ! this is thread : {0} ",i);
        Thread.Sleep(10);
}

public static void Main(String[] args)
{
    int i;
    for (i = 0; i < 10; i++)
    {
        Thread th1 = new Thread(()=>tone(i) );
        th1.Start();
       // Console.WriteLine(i);
    }
    Console.WriteLine("hey there!");
    Console.ReadLine();
}

}

在此輸入圖像描述

由於關閉

將您的代碼更改為:

int i;
    for (i = 0; i < 10; i++)
    {
       int j = i;
        Thread th1 = new Thread(()=>tone(j) );
        th1.Start();
       // Console.WriteLine(i);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM