进程是不活泼的。若要使进程完成某项操作,它必须拥有一个在它的环境中运行的线程,该线程负责执行包含在进程的地址空间中的代码。实际上,单个进程可能包含若干个线程,所有这些线程都“同时”执行进程地址空间中的代码。为此,每个线程都有它自己的一组CPU寄存器和它自己的堆栈。每个进程至少拥有一个线程,来执行进程的地址空间中的代码。如果没有线程来执行进程的地址空间中的代码,那么进程就没有存在的理由了,系统就将自动撤消该进程和它的地址空间。若要使所有这些线程都能运行,操作系统就要为每个线程安排一定的CPU时间。它通过以一种循环方式为线程提供时间片(称为量程),造成一种假象,仿佛所有线程都是同时运行的一样。如果计算机拥有多个CPU,那么操作系统就要使用复杂得多的算法来实现CPU上线程负载的平衡。当创建一个进程时,系统会自动创建它的第一个线程,称为主线程。然后,该线程可以创建其他的线程,而这些线程又能创建更多的线程。
using System.Threading;// The ThreadWithState class contains the information needed for
// a task, and the method that executes the task.
//
namespace Test
{
public class ThreadWithState
{
// State information used in the task.
private string boilerplate;
private int value; // The constructor obtains the state information.
public ThreadWithState(string text, int number)
{
boilerplate = text;
value = number;
}
// The thread procedure performs the task, such as formatting
// and printing a document.
public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
}
} // Entry point for the example.
//
public class Example
{
public static void Main()
{
// Supply the state information required by the task.
ThreadWithState tws =
new ThreadWithState("This report displays the number {0}.", 42);
// Create a thread to execute the task, and then
// start the thread.
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join();
Console.WriteLine("Independent task has completed; main thread ends.");
Console.ReadLine();
}
}
}请问各位老师,这个例子如何理解呀?
简单的说进程是一个应用程序域,如你的一个正在运行的程序...
线程则包含在进程中,并且一个进程可以存在多个线程...详细资料到网上搜一下,很多...引用一下楼上的。。呵呵!
在一个进程中添加两个或者以上的线程,其中的执行顺序,和状态,执行的优先级别,你可以看看详细的资料。MSDN上时很详细的!