C#語法學習線程(Thread)

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2008/9/11
 * Time: 下午 02:36
 * 
 
*/
using  System;
using  System.Threading;
class  SingleThread
{
    
static   void  Main( string  [] args)
    {
        SingleThread st 
= new  SingleThread();
        Thread th 
= new  Thread( new  ThreadStart(st.SayHello));
        th.Start();
    }
    
public   void  SayHello()
    {
        Console.WriteLine(
" Hello from a single thread. " );
    }
}

/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 2008/9/11
 * Time: 下午 02:41
 * 
 
*/

using  System;
using  System.Threading;
class  SyncData
{
    
int  index = 0 ;
    
string [] comment = new   string []{ " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " 十一 " , " 十二 " , " 十三 " , " 十四 " , " 十五 " , " 十六 " , " 十七 " , " 十八 " , " 十九 " , " 二十 " }; 
    
public   string  GetNetComment()
    {
        
lock ( this )
        {
            
if (index < comment.Length)
            {
                
return  comment[index ++ ];
            }
            
else
            {
                
return   " empty " ;
            }
        }
    }
}
class  Synchronization
{
    SyncData sdat
= new  SyncData();
    
public   void  GetComments()
    {
        
string  comment;
        
do
        {
            comment
= sdat.GetNetComment();
            Console.WriteLine(
" Current Thread:{0},comment:{1} " ,Thread.CurrentThread.Name,comment);
        }
while (comment != " empty " );
    }
    
    
static   void  Main( string [] args)
    {
        Synchronization sync
= new  Synchronization();
        Thread t1
= new  Thread( new  ThreadStart(sync.GetComments));
        Thread t2
= new  Thread( new  ThreadStart(sync.GetComments));
        Thread t3
= new  Thread( new  ThreadStart(sync.GetComments));
        t1.Name
= " Thread 1 " ;
        t2.Name
= " Thread 2 " ;
        t3.Name
= " Thread 3 " ;
        t1.Start();
        t2.Start();
        t3.Start();
    }
}

你可能感兴趣的:(thread)