zoukankan      html  css  js  c++  java
  • C#多线程的用法1-简单示例

    写在前面:阅读本系列文章即表示你已经知道什么是线程等理论知识,现在正想了解如何正确的使用线程进行编程工作。

    /// <summary>
    /// 单线程工作示例
    /// </summary>
    private static void SingleThreadDemo()
    {
    Console.WriteLine("Main Thread");
    Thread thread = new Thread(() =>
    {
    for (var i = 0; i < 10; i++)
    {
    Console.WriteLine(String.Format("Thread Out:{0}", i));
    Thread.Sleep(500);
    }
    Console.WriteLine("Sub Thread The End");
    });
    thread.Start();
    Console.WriteLine("Main Thread Wait For Sub Thread");
    }
    /// <summary>
    /// 多个线程工作示例
    /// </summary>
    private static void MultiThreadDemo()
    {
    ThreadStart task = () =>
    {
    for (var i = 0; i < 10; i++)
    {
    Console.WriteLine(String.Format("Thread {0} Out:{1}", Thread.CurrentThread.Name, i));
    Thread.Sleep(500);
    }
    Console.WriteLine(String.Format("Sub Thread {0} The End", Thread.CurrentThread.Name));
    };
    Console.WriteLine("Main Thread");
    Thread thread1 = new Thread(task)
    {
    Name = "thread1"
    };
    thread1.Start();
    Thread thread2 = new Thread(task)
    {
    Name = "thread2"
    };
    thread2.Start();
    Thread thread3 = new Thread(task)
    {
    Name = "thread3"
    };
    thread3.Start();
    Console.WriteLine("Main Thread Wait For Sub Thread");
    }
    
     
    
    static void Main(string[] args)
    {
    //SingleThreadDemo();
    //MultiThreadDemo();
    Console.ReadLine();
    }
    

      

  • 相关阅读:
    GIL 全局解释器
    线程
    队列 Queue 与 生产者消费模型
    进程 与 并发(进程打开方式,互斥锁)
    【JAVA设计模式】单例模式
    【排序】桶排序
    【排序】选择排序
    【排序】插入排序
    【排序】冒泡排序
    JVM 优化之逃逸分析
  • 原文地址:https://www.cnblogs.com/dw039/p/7397685.html
Copyright © 2011-2022 走看看