다음을 통해 공유


Thread 클래스

스레드를 만들고 제어하며, 해당 속성을 설정하고, 상태를 가져옵니다.

네임스페이스: System.Threading
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
Public NotInheritable Class Thread
    Inherits CriticalFinalizerObject
    Implements _Thread
‘사용 방법
Dim instance As Thread
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
public sealed class Thread : CriticalFinalizerObject, _Thread
[ComVisibleAttribute(true)] 
[ClassInterfaceAttribute(ClassInterfaceType::None)] 
public ref class Thread sealed : public CriticalFinalizerObject, _Thread
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
public final class Thread extends CriticalFinalizerObject implements _Thread
ComVisibleAttribute(true) 
ClassInterfaceAttribute(ClassInterfaceType.None) 
public final class Thread extends CriticalFinalizerObject implements _Thread

설명

프로세스는 하나 이상의 스레드를 만들어 해당 프로세스와 관련된 프로그램 코드 부분을 실행할 수 있습니다. 스레드가 실행하는 프로그램 코드를 지정하려면 ThreadStart 대리자 또는 ParameterizedThreadStart 대리자를 사용합니다. ParameterizedThreadStart 대리자를 사용하여 스레드 프로시저에 데이터를 전달할 수 있습니다.

스레드는 존재하는 동안 항상 ThreadState에서 정의하는 상태 중 하나 이상으로 존재합니다. 스레드에 대해 ThreadPriority에서 정의하는 예약 우선 순위를 요청할 수 있지만 운영 체제에서 해당 우선 순위를 사용할지는 보장할 수 없습니다.

GetHashCode는 관리되는 스레드에 대한 ID를 제공합니다. 스레드는 수명 동안, 값을 가져오는 응용 프로그램 도메인에 관계없이 다른 스레드의 값과 충돌하지 않습니다.

참고

관리되지 않는 호스트는 관리되는 스레드와 관리되지 않는 스레드 간의 관계를 제어할 수 있으므로 운영 체제 ThreadId는 관리되는 스레드와 고정 관계가 없습니다. 특히, 정교한 호스트에서는 CLR 호스팅 API를 사용하여 동일한 운영 체제 스레드에 대해 관리되는 여러 스레드를 예약하거나 여러 다른 운영 체제 스레드 사이로 관리되는 스레드를 이동할 수 있습니다.

예제

다음 코드 예제에서는 단순 스레딩 기능을 보여 줍니다.

Imports System
Imports System.Threading

' Simple threading scenario:  Start a Shared method running
' on a second thread.
Public Class ThreadExample
    ' The ThreadProc method is called when the thread starts.
    ' It loops ten times, writing to the console and yielding 
    ' the rest of its time slice each time, and then ends.
    Public Shared Sub ThreadProc()
        Dim i As Integer
        For i = 0 To 9
            Console.WriteLine("ThreadProc: {0}", i)
            ' Yield the rest of the time slice.
            Thread.Sleep(0)
        Next
    End Sub

    Public Shared Sub Main()
        Console.WriteLine("Main thread: Start a second thread.")
        ' The constructor for the Thread class requires a ThreadStart 
        ' delegate.  The Visual Basic AddressOf operator creates this
        ' delegate for you.
        Dim t As New Thread(AddressOf ThreadProc)
        ' Start ThreadProc.  On a uniprocessor, the thread does not get 
        ' any processor time until the main thread yields.  Uncomment 
        ' the Thread.Sleep that follows t.Start() to see the difference.
        t.Start()
        'Thread.Sleep(0)

        Dim i As Integer
        For i = 1 To 4
            Console.WriteLine("Main thread: Do some work.")
            Thread.Sleep(0)
        Next

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.")
        t.Join()
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.")
        Console.ReadLine()
    End Sub
End Class
using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample {
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }

    public static void Main() {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProc));
        // Start ThreadProc.  On a uniprocessor, the thread does not get 
        // any processor time until the main thread yields.  Uncomment 
        // the Thread.Sleep that follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
        Console.ReadLine();
    }
}
// [C++]
// Compile using /clr option.
using namespace System;
using namespace System::Threading;

// Simple threading scenario:  Start a Shared method running
// on a second thread.
public ref class ThreadExample
{
public:

   // The ThreadProc method is called when the thread starts.
   // It loops ten times, writing to the console and yielding 
   // the rest of its time slice each time, and then ends.
   static void ThreadProc()
   {
      for ( int i = 0; i < 10; i++ )
      {
         Console::Write(  "ThreadProc: " );
         Console::WriteLine( i );
         
         // Yield the rest of the time slice.
         Thread::Sleep( 0 );

      }
   }

};

int main()
{
   Console::WriteLine( "Main thread: Start a second thread." );
   
   // Create the thread, passing a ThreadStart delegate that
   // represents the ThreadExample::ThreadProc method.  For a 
   // delegate representing a static method, no object is
   // required.
   Thread^ oThread = gcnew Thread( gcnew ThreadStart( &ThreadExample::ThreadProc ) );
   
   // Start the thread.  On a uniprocessor, the thread does not get 
   // any processor time until the main thread yields.  Uncomment
   // the Thread.Sleep that follows t.Start() to see the difference.
   oThread->Start();
   
   //Thread::Sleep(0);
   for ( int i = 0; i < 4; i++ )
   {
      Console::WriteLine(  "Main thread: Do some work." );
      Thread::Sleep( 0 );

   }
   Console::WriteLine(  "Main thread: Call Join(), to wait until ThreadProc ends." );
   oThread->Join();
   Console::WriteLine(  "Main thread: ThreadProc.Join has returned.  Press Enter to end program." );
   Console::ReadLine();
   return 0;
}
import System.*;
import System.Threading.*;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample
{
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProc() throws InterruptedException
    {
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("ThreadProc: {0}", System.Convert.ToString(i));
            // Yield the rest of the time slice.
            Thread.sleep(0);
        }
    } //ThreadProc

    public static void main(String[] args) throws InterruptedException
    {
        Console.WriteLine("Main thread: Start a second thread.");

        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  J# simplifies the creation of this delegate.
        System.Threading.Thread t =
            new System.Threading.Thread(new ThreadStart(ThreadProc));

        // Start ThreadProc.  On a uniprocessor, the thread does not get 
        // any processor time until the main thread yields.  Uncomment 
        // the Thread.Sleep that follows t.Start() to see the difference.
        t.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++) {
            Console.WriteLine("Main thread: Do some work.");
            Thread.sleep(0);
        }
        Console.WriteLine("Main thread: Call Join(), to wait until "
            + "ThreadProc ends.");
        t.Join();
        Console.WriteLine("Main thread: ThreadProc.Join has returned."
            + "  Press Enter to end program.");
        Console.ReadLine();
    } //main
} //ThreadExample

이 코드는 다음과 유사하게 출력됩니다.

 [VB, C++, C#]
 Main thread: Start a second thread.
 Main thread: Do some work.
 ThreadProc: 0
 Main thread: Do some work.
 ThreadProc: 1
 Main thread: Do some work.
 ThreadProc: 2
 Main thread: Do some work.
 ThreadProc: 3
 Main thread: Call Join(), to wait until ThreadProc ends.
 ThreadProc: 4
 ThreadProc: 5
 ThreadProc: 6
 ThreadProc: 7
 ThreadProc: 8
 ThreadProc: 9
 Main thread: ThreadProc.Join has returned.  Press Enter to end program.

상속 계층 구조

System.Object
   System.Runtime.ConstrainedExecution.CriticalFinalizerObject
    System.Threading.Thread

스레드로부터의 안전성

이 형식은 다중 스레드 작업을 수행하는 데 안전합니다.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

Thread 멤버
System.Threading 네임스페이스

기타 리소스

스레드 및 스레딩
스레드 및 스레딩 사용