1、正常,同时开启两个线程
//启动函数 public void Test() { Thread thread1 = new Thread(() => SC1()); thread1.Start(); Thread thread2 = new Thread(() => SC2()); thread2.Start(); } public void SC1() { for (int i = 0; i < 50; i++) { Thread.Sleep(1000); Console.WriteLine("====我是SC1===="); } } public void SC2() { for (int i = 0; i < 50; i++) { Thread.Sleep(1000); Console.WriteLine("====我是SC2===="); } }View Code
2、有序执行,无并发
//启动函数 public void Test() { Thread thread1 = new Thread(() => SC1()); thread1.Start(); Thread thread2 = new Thread(() => SC2()); thread2.Start(); } int sc1 = 0; int sc2 = 0; public void SC1() { if (Interlocked.Exchange(ref sc1, 1) == 0) { if (sc2 == 0) { for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.WriteLine("====我是SC1===="); } } } Interlocked.Exchange(ref sc1, 0); } public void SC2() { while (true) { if (sc1 == 0) { if (Interlocked.Exchange(ref sc2, 1) == 0) { for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.WriteLine("====我是SC2===="); } break; } } } Interlocked.Exchange(ref sc2, 0); }View Code
3、其他
标签:Thread,记录,C#,void,int,测试,SC1,public,SC2 From: https://www.cnblogs.com/chenze-Index/p/16607169.html