// C#
Thread thread = new Thread(() => Console.WriteLine("새로운 스레드 실행"));
thread.Start();
// C#
thread.Join(); // thread가 완료될 때까지 대기
// thread가 완료 되어야 다음 코드가 실행
lock (lockObject)
{
sharedResource++;
}
스레드를 사용하는 이유는 프로그램이 효율적으로 동시에 여러 작업을 처리할 수 있도록 하기 위해서입니다. 특히, 시간이 오래 걸리는 작업이나 동시다발적인 요청 처리를 필요로 하는 환경에서 스레드는 필수적인 도구입니다.
예를 들어, 이미지 처리, 데이터 분석, 암호화와 같은 작업은 계산이 많기 때문에 병렬로 실행하면 속도가 빨라집니다.
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread1 = new Thread(() => ProcessData("작업 1"));
Thread thread2 = new Thread(() => ProcessData("작업 2"));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
Console.WriteLine("모든 작업 완료!");
}
static void ProcessData(string taskName)
{
Console.WriteLine($"{taskName} 시작...");
Thread.Sleep(2000); // 데이터 처리 시뮬레이션
Console.WriteLine($"{taskName} 완료!");
}
}
두 작업이 병렬로 실행되므로 처리 시간이 절반으로 줄어듭니다.
작업 1 시작...
작업 2 시작...
(2초 후)
작업 1 완료!
작업 2 완료!
모든 작업 완료!
사용자가 "파일 다운로드" 버튼을 클릭하면 다운로드 작업을 백그라운드 스레드에서 실행하고, 메인 스레드는 계속 UI를 처리합니다.
using System;
using System.Threading;
using System.Windows.Forms;
public class MainForm : Form
{
private Button downloadButton;
public MainForm()
{
downloadButton = new Button { Text = "파일 다운로드", Dock = DockStyle.Top };
downloadButton.Click += (sender, e) =>
{
Thread thread = new Thread(DownloadFile);
thread.Start(); // 백그라운드에서 실행
};
Controls.Add(downloadButton);
}
private void DownloadFile()
{
Console.WriteLine("파일 다운로드 중...");
Thread.Sleep(5000); // 다운로드 시뮬레이션
Console.WriteLine("다운로드 완료!");
}
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
}
using System;
using System.Threading;
class Program
{
static void Main()
{
for (int i = 1; i <= 3; i++)
{
int clientId = i;
Thread thread = new Thread(() => HandleRequest(clientId));
thread.Start();
}
}
static void HandleRequest(int clientId)
{
Console.WriteLine($"클라이언트 {clientId} 요청 처리 중...");
Thread.Sleep(3000); // 요청 처리 시뮬레이션
Console.WriteLine($"클라이언트 {clientId} 요청 완료!");
}
}
클라이언트 1 요청 처리 중...
클라이언트 2 요청 처리 중...
클라이언트 3 요청 처리 중...
(3초 후)
클라이언트 1 요청 완료!
클라이언트 2 요청 완료!
클라이언트 3 요청 완료!