本次循环不该打印时,让线程代码自旋;等待另外的线程递增而引起本线程再次进入业务代码。
volatile static int i = 0; public static void Main(String[] args) { Thread thread1 = new Thread(() => { while (i <= 100) { if (i % 2 == 0) { Console.WriteLine(i + "== 偶数"); i++; } } }); Thread thread2 = new Thread(() => { while (i <= 100) { if (i % 2 ==1 ) { Console.WriteLine(i + "== 奇数"); i++; } } }); thread1.Start(); thread2.Start(); Console.ReadKey(); }
翻译成golang
因为go不支持while 和do-while语法,可以通过for
关键字来实现:
即break在业务代码执行前相当与while,break在业务代码执行后相当do...while。
package main import ( "fmt" "strconv" "sync" ) var wg sync.WaitGroup var i int = 0 func main() { wg.Add(2) go func() { defer wg.Done() for { if i > 100 { break } if i%2 == 0 { fmt.Println("g0: " + strconv.Itoa(i)) i++ } } }() go func() { defer wg.Done() for { if i > 100 { break } if i%2 == 1 { fmt.Println("g1: " + strconv.Itoa(i)) i++ } } }() wg.Wait() }