// 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(); } }
此代码产生的输出类似如下内容:
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.?