C# 中使用多執行緒呼叫一個靜態函式是否會產生執行緒安全問題
阿新 • • 發佈:2020-12-25
技術標籤:CSharp
如題 在開發系統時 多個類需要呼叫同一個靜態方法有可能會同時發生, 靜態方法中沒有靜態變數 那麼會不會出現執行緒安全問題呢
如下測試
開啟 3 個執行緒 執行緒睡眠時間逐漸減少 共同呼叫同一個靜態方法 靜態方法輸出傳入得形參並顯示 如果出現問題那麼輸出結果就會亂,多次執行 結果相同 那麼認為該情況下不會產生執行緒安全問題
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(() => testClass.Func(300,1, 1));
t1.Start();
Thread t2 = new Thread(() => testClass.Func(10, 2, 2));
t2.Start();
Thread t3 = new Thread(( ) => testClass.Func(0, 3, 3));
t3.Start();
Console.Read();
}
}
public class testClass
{
public static void Func(int sleepTime,int flag,int callCount)
{
Thread.Sleep(sleepTime);
Console.WriteLine("func is called {0} time ,flag is {0}" , callCount, flag);
}
}
}