Zum Inhalt springen

Arbeiten mit .NET: Das Framework/ Anhang/ Mehr zu Threads

Aus Wikibooks

Wofür dieser Code sinnvoll ist, ist noch ziemlich ungeklärt.

<span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Threading; <span class="rem">//erforderlich</span>

<span class="kwrd">namespace</span> Wiki
{
  <span class="kwrd">class</span> Program
  {
    <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
    {
      <span class="rem">//Sowohl einzelne Threads</span>
      Thread t1 = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ParameterizedThreadStart(PrintHello));
      Thread t2 = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ParameterizedThreadStart(PrintHello));
      Thread t3 = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ParameterizedThreadStart(PrintHello));

      <span class="rem">//Als auch ThreadArrays sind möglich</span>
      Thread[] t = <span class="kwrd">new</span> Thread[5];
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i < t.Length; i++)
      {
        t[i] = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ParameterizedThreadStart(PrintHi));
      }

      Console.WriteLine(<span class="str">"Test t1,t2,t3"</span>);

      t1.Start((<span class="kwrd">object</span>)<span class="str">"Welt"</span>);
      t2.Start((<span class="kwrd">object</span>)<span class="str">"Jan"</span>);
      t3.Start();

      Console.WriteLine(<span class="str">"Test t-Array"</span>);

      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i < t.Length; i++)
      {
        t[i].Start((<span class="kwrd">object</span>)Convert.ToString(i));
      }

      Console.WriteLine(<span class="str">"Das Programm läuft weiter"</span>);

      Console.Read();
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PrintHello(<span class="kwrd">object</span> x)
    {
      <span class="rem">//Unboxing</span>
      <span class="kwrd">string</span> t = (<span class="kwrd">string</span>)x;
      <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i < 20; i++)
      {
        Console.WriteLine(<span class="str">"Hello "</span> + t);
      }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> PrintHi(<span class="kwrd">object</span> y){
      <span class="kwrd">string</span> t = (<span class="kwrd">string</span>)y;
      <span class="kwrd">for</span>(<span class="kwrd">int</span> i=0; i<20; i++){
        Console.WriteLine(<span class="str">"Hi "</span>+t);
      }}
  }
}