在C#中,ThreadLocal
類用于在每個線程中存儲線程特定的數據。然而,ThreadLocal
本身并不能直接處理線程中斷。線程中斷是通過調用Thread.Interrupt()
方法來設置的,當線程處于阻塞狀態(如等待I/O操作完成)時,調用此方法會引發InterruptedException
異常。
要在ThreadLocal
中處理線程中斷,您需要在每個線程中處理InterruptedException
異常。這通常是通過在一個循環中捕獲異常并檢查中斷狀態來實現的。下面是一個示例:
using System;
using System.Threading;
class Program
{
private static readonly ThreadLocal<int> threadLocal = new ThreadLocal<int>();
static void Main()
{
Thread thread1 = new Thread(Thread1);
Thread thread2 = new Thread(Thread2);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void Thread1()
{
while (!Thread.CurrentThread.IsInterrupted)
{
try
{
// 模擬一些工作
Thread.Sleep(1000);
// 設置ThreadLocal值
threadLocal.Value = 42;
Console.WriteLine($"Thread1: {threadLocal.Value}");
}
catch (InterruptedException ex)
{
// 處理中斷異常
Console.WriteLine("Thread1: Interrupted");
Thread.ResetInterrupt(); // 重置中斷狀態
break;
}
}
}
static void Thread2()
{
while (!Thread.CurrentThread.IsInterrupted)
{
try
{
// 模擬一些工作
Thread.Sleep(1000);
// 設置ThreadLocal值
threadLocal.Value = 99;
Console.WriteLine($"Thread2: {threadLocal.Value}");
}
catch (InterruptedException ex)
{
// 處理中斷異常
Console.WriteLine("Thread2: Interrupted");
Thread.ResetInterrupt(); // 重置中斷狀態
break;
}
}
}
}
在這個示例中,我們創建了兩個線程,每個線程都有自己的ThreadLocal
實例。在每個線程的工作循環中,我們捕獲InterruptedException
異常并處理它。如果線程被中斷,我們會重置中斷狀態并退出循環。這樣,您就可以在ThreadLocal
中處理線程中斷了。