C#高级程序线程的使用

C#高级程序设计

一. C#线程的使用

  1. 分别打印
    代码如下:
在这里插入代码片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace _08分别打印1_100
{
//课堂练习:写两个线程,交替着分别打印1-100,看谁先执行完
 class Program
{
static bool b = true;
static void Main(string[] args)
{
	Thread t1 = new Thread(M);
     t1.Name = "t1";
     Thread t2 = new Thread(M);
     t2.Name = "--";
     //t1.Priority = ThreadPriority.Highest;//线程优先级:有五种优先级
     //t1.Priority = ThreadPriority.Lowest;
     t1.Start();//通知cpu线程t1准备好
     t2.Priority = ThreadPriority.Highest;
     t2.Start();//通知cpu线程t2准备
     
     Console.ReadKey();
     
     public static void M()
     {
	//当一个线程达到100时,另一个线程终止
	for (int i = 1; i < 101; i++)
	{
		Thread.Sleep(1);
		if (b)
         {
         if (i == 100)
         {
         	b = false;
         }
         Console.WriteLine(Thread.CurrentThread.Name + ":" + i);//拿到当前线程名字Thread.CurrentThread.Name
         }
	}
}

  1. 交替打印
    代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;码片

namespace _07交替打印1_100
{
//课堂练习:写两个线程,交替打印1-100,看谁先执行完
//ThreadState的四种状态:就绪状态(调用start方法之前) 运行状态(调用start方法之后) 死亡状态(运行结束之后) 阻塞状态(是指线程在等待一个事件(如某个信号量),逻辑上不可执行)
     class Program
     {
        static int a = 0;
        static bool b = true;
        static void Main(string[] args)
     }
     {
            Thread t1 = new Thread(M);
            t1.Name = "t1";
            Thread t2 = new Thread(M);
            t2.Name = "--";
            t1.Priority = ThreadPriority.Highest;//线程优先级:有五种优先级
            t1.Start();//通知cpu线程t1准备好
            t2.Start();//通知cpu线程t2准备好
            
            Console.ReadKey();
     }
             public static void M()
        {
            //当一个线程达到50时,另一个线程终止
            for (int i = 1; i < 51; i++)
            {
                Thread.Sleep(1);
                if (b)
                {
                    if (i == 50)
                    {
                        b = false;
                    }
                    a++;
                    Console.WriteLine(Thread.
                    CurrentThread.Name + ":" + a);//拿到当前线程名字Thread.CurrentThread.Name                    
                }
            }
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值