title: C# MultiThread without duplication
body: <p>This is my code:</p>
  
  <pre><code>    Thread _th1, _th2, _th3, _th4;
  int _i;
  
      void thMethod()
      {
          while(_i &lt; 100){
              Thread.Sleep((new Random()).Next(1,500));
              Application.DoEvents();
              Console.WriteLine(_i);
              _i++;
          }
      }
  
      private void button4_Click(object sender, EventArgs e)
      {
          _th1 = new Thread(new ThreadStart(thMethod));
          _th1.Start();
          _th2 = new Thread(new ThreadStart(thMethod));
          _th2.Start();
          _th3 = new Thread(new ThreadStart(thMethod));
          _th3.Start();
          _th4 = new Thread(new ThreadStart(thMethod));
          _th4.Start();
      }
  </code></pre>
  
  <p>What i want to do is,
  doing Console.WriteLine from 0 to 99 using multithread,
  and the delay is random.</p>
  
  <p>However, my code prints duplicated numbers</p>
  
  <p>well, this is the result.</p>
  
  <p>0
  1
  2
  2
  4
  5
  6
  7
  8
  9
  10
  10
  12
  13
  14
  14
  16
  16
  18
  19
  20
  20
  22
  22
  24
  24
  26
  26
  28
  28
  30
  31
  32
  33
  34
  35
  36
  36
  38
  39
  40
  40
  42
  42
  44
  44
  46
  46
  48
  49
  50
  50
  52
  52
  54
  54
  56
  56
  58
  58
  60
  60
  62
  62
  64
  65
  66
  66
  68
  68
  70
  70
  72
  72
  74
  74
  76
  76
  78
  78
  80
  80
  82
  82
  84
  84
  86
  87
  88
  88
  90
  90
  92
  92
  94
  94
  96
  96
  98
  98
  100
  101
  102</p>
  
  <p>As you see, there are duplicated numbers printed,
  and it does not even stop at 99.</p>
  
  <p>So... How to correct this code in order to make it run properly?</p>
  
  <p>====================== Do i have to change like..</p>
  
  <pre><code>    void thMethod()
      {
          while(_i &lt; 100){
              Thread.Sleep((new Random()).Next(1,500));
              Application.DoEvents();
              Interlocked.Increment(ref _i);
              Console.WriteLine(_i);
          }
      }
  </code></pre>
  
  <p>this?</p>