程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#語法學習:線程(Thread)

C#語法學習:線程(Thread)

編輯:關於C語言
/*
* 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();
}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved