C#:线程(3):线程暂停

线程暂停是让某一个线程先休眠一段时间,在这段时间内,该线程不占用系统资源

用一个例子说明线程休眠,除了主函数还有另一个线程,主函数会输出从11到19的数字,而线程会每隔两秒输出从1到9的数

(一):首先建立控制台程序

在预处理部分写入

using static System.Console;

在主函数下写入

 System.Threading.Thread t = new System.Threading.Thread(PrintNumbersWithDelay);
 t.Start();
PrintNumbers();

ReadKey();

编写没有延迟的输出函数

        static void PrintNumbers()
        {
            WriteLine("Starting...");
            for (int i = 1; i < 10; i++)
            {
                WriteLine(i+10);
            }
        }

编写有延迟的输出函数

        static void PrintNumbersWithDelay()
        {
            WriteLine("Thread starting...");
            for (int i = 1; i < 10; i++)
            {
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
                WriteLine(i);
            }
        }

(二):运行

结果如下

(三):小结

这个案例真的不算难,但是用来理解线程的作用我觉得还是ok的。我理解线程是仿照C语言的面向过程编程,在使用C语言时,有一个主函数,从头执行到尾,执行完了,程序就结束。如果把像C这样从头执行到尾称为一个执行流,那么线程其实就是多执行流的一个编程模式。

我花了一个简单的示意图,可以看到,当主程序运行到t.Start();一句时,产生了一个新的执行流,也就是t线程,我使用了了一个向下的分支表示在t线程开始之前,主函数还要执行若干语句,放在本例中,就是在输出“Thread starting...”之前输出的数字。当新线程t建立后,新线程就要开始和主程序抢占cpu时间

在图中我们用黑色线表示用于该线程的cpu时间,如果没有特意处理(比如说本例用到的语句),cpu用于各线程之间的时间是基本平均的,而且随机性比较强,作为程序员我们很难知道程序在哪个语句后会跳到另一个线程去执行。

在本例中使用了一个Sleep()语句,其作用是告诉系统,接下来若干时间内不要执行本线程的代码,系统接受到这样的消息之后,就会把接下来的cpu运算时间分配给其他线程

(四):源代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using static System.Console;

namespace Ch1Re2
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Threading.Thread t = new System.Threading.Thread(PrintNumbersWithDelay);
            t.Start();
            PrintNumbers();

            ReadKey();
        }

        static void PrintNumbers()
        {
            WriteLine("Starting...");
            for (int i = 1; i < 10; i++)
            {
                WriteLine(i+10);
            }
        }

        static void PrintNumbersWithDelay()
        {
            WriteLine("Thread starting...");
            for (int i = 1; i < 10; i++)
            {
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2));
                WriteLine(i);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/buaazyp/article/details/81110176