1、使用chanel
func main() { done := make(chan bool) ticker := time.NewTicker(time.Millisecond * 1000) go func() { total := 0 for t := range ticker.C { fmt.Println("Tick at:", t) total += 1 if total > 10 { break } } done <- true }() <-done ticker.Stop() }
2 、使用waigroup
func main() { var wg sync.WaitGroup wg.Add(1) ticker := time.NewTicker(time.Millisecond * 1000) go func() { total := 0 for t := range ticker.C { fmt.Println("Tick at:", t) total += 1 if total > 10 { break } } wg.Done() }() wg.Wait() ticker.Stop() }
有疑问加站长微信联系(非本文作者)