這裡為什麼會出現多線程?原因是DebugLZQ在寫一個LINQ綜合Demo的時候遇到了多線程
using System;
using System
using System
using System
using System
namespace 多線程 {
class Program
{
static void Main(string[] args)
{
Console
Thread t = new Thread(new ThreadStart(ShowTime));//注意ThreadStart委托的定義形式
t
Console
//while (t
Thread
t
t
Console
Console
}
static void ShowTime()
{
while (true)
{
Console
}
}
}
}
注意ThreadStart委托的定義如下:
可見其對傳遞進來的函數要求是:返回值void
using System;
using System
using System
using System
using System
namespace 多線程
class Program
{
static void Main(string[] args)
{
Console
Thread t = new Thread(new ParameterizedThreadStart(DoSomething));//注意ParameterizedThreadStart委托的定義形式
t
Console
Thread
t
t
Console
}
static void DoSomething(object s)
{
string[] strs = s as string[];
while (true)
{
Console
}
}
}
}
注意ParameterizedThreadStart委托的定義如下:
可見其對傳入函數的要求是:返回值void
using System;
using System
sing System
using System
using System
namespace 多線程
class Program
{
static void Main(string[] args)
{
Guest guest = new Guest()
{
Name=
};
Thread t = new Thread(new ThreadStart(guest
t
Thread
t
t
Console
}
}
//
class Guest
{
public string Name { get; set; }
public int Age { get; set; }
public void DoSomething()
{
while (true)
{
Console
}
}
}
}
這個還是使用ThreadStart委托
兩種方法
線程同步的方法有很多很多種volatile
這裡用lock說明問題:在哪裡同步
首先感受下不同步會出現的問題:
代碼就是下面的代碼去掉lock塊
using System;
using System
using System
using System
using System
namespace 多線程
class Program
{
static object obj = new object();//同步用
static int balance =
static void Main(string[] args)
{
Thread t
t
Thread t
t
Console
}
static void Credit()
{
for (int i =
{
lock (obj)
{
balance +=
Console
}
}
}
static void Debit()
{
for (int i =
{
lock (obj)
{
balance
Console
}
}
}
}
}
小結:多線程調用函數就是這樣
From:http://tw.wingwit.com/Article/program/net/201311/12352.html