- class ThreadUse
- {
- public int count = 0;
- //定义一个对象用做锁
- ThreadUser user=new ThreadUser();
- public void CountAdd()
- {
- //锁住线程,只允许挨个访问,不允许多个线程同时访问
- lock(user){
- for (int i = 1; i <= 100; i++)
- {
- Console.WriteLine(count++);
- }
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- ThreadUse threaduse = new ThreadUse();
- Thread thread2 = new Thread(threaduse.CountAdd);
- thread2.Name = "线程2";
- Thread thread3 = new Thread(threaduse.CountAdd);
- thread3.Name = "线程3";
- thread2.Start();
- thread3.Start();
- //thread2.Abort();
- //thread3.Abort();
- //Console.WriteLine(threaduse.count);
- Console.ReadKey();
- }
- }
复制代码 其实,线程同步涉及到锁的概念。因为你们以后才会接触到,现在说到这里可能会很迷茫
多线程的执行顺序是不可预测的,多执行一行代码和少执行一行代码 结果当然不一样。
|