• C# 多线程编程 使用Thread类创建线程


    使用Thread类可以创建和控制线程。使用Thread类需要引入系统的System.Threading命名空间。

    下面简单示例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ThreadDemo
    {
        class Program
        {
            static void ThreadMain()
            {
                Console.WriteLine("Running in the thread {0}, id: {1}",Thread.CurrentThread.Name, Thread.CurrentThread.ManagedThreadId);
            }
    
            static void Main(string[] args)
            {
                Thread t1 = new Thread(ThreadMain);
                t1.Name = "MyThread";
                t1.Start();
                Console.WriteLine("This is the Main thread");
    
                Console.ReadKey();            
            }
        }
    }
    

    这里不能保证哪个结果显输出,线程由操作系统调度,每次哪个线程在前面是不同的。

    使用Thread类创建的线程默认的是前台线程,线程池中的线程总是后台线程。

    • 前台线程
    • 后台线程

    前台线程在Main方法结束后,还会执行,一直到所有前台线程都完成任务了,程序才会结束。

    后台线程在Main方法结束的时候,也会随之一起结束。

    后台线程非常适合完成后台任务。例如关闭WORD应用程序,拼写检查继续运行其进程就没有意义。这样可以将这个进程设置为后台进程。

    通过设置线程的IsBackground属性可以设置是否为后台进程。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace ForegroundThread
    {
        class Program
        {
            static void Main(string[] args)
            {
                Thread t1 = new Thread(ThreadMain);
                t1.Name = "MyNewThread1";
                t1.IsBackground = true;
                t1.Start();
                Console.WriteLine("Main Thread ending now...");
            }
    
            static void ThreadMain()
            {
                Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
                Thread.Sleep(3000);
                Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
            }
        }
    }
    
  • 相关阅读:
    Linux下软件安装方法即路径设置
    maven和jdk版本不匹配
    jobTracker 和taskTracker
    任务调度quartz
    springside3.1.8打包
    给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组
    二进制求和
    数组中找到目标值,并返回其索引
    加1问题
    给定字符串返回最后一个单词的长度
  • 原文地址:https://www.cnblogs.com/herbert/p/1765240.html
Copyright © 2020-2023  润新知