1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. func main() {
    7. start := time.Now()
    8. c := make(chan interface{})
    9. go func() {
    10. time.Sleep(5 * time.Second)
    11. close(c)
    12. }()
    13. fmt.Println("Blocking on read...")
    14. select {
    15. case a, b := <-c:
    16. fmt.Println(a, b)
    17. fmt.Printf("Unblocked %v later. \n", time.Since(start))
    18. }
    19. }
    20. 输出:
    21. Blocking on read...
    22. <nil> false
    23. Unblocked 5.0137958s later.

    image.png
    image.png
    image.png

    1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. func main() {
    7. done := make(chan interface{})
    8. go func() {
    9. time.Sleep(5 * time.Second)
    10. close(done)
    11. }()
    12. workCounter := 0
    13. loop:
    14. for {
    15. select {
    16. case <-done:
    17. break loop
    18. default:
    19. fmt.Println("xxx")
    20. }
    21. workCounter++
    22. time.Sleep(1 * time.Second)
    23. }
    24. fmt.Printf("Achieved %v cycles of work before signalled to stop.\n", workCounter)
    25. }
    26. 输出:
    27. xxx
    28. xxx
    29. xxx
    30. xxx
    31. xxx
    32. Achieved 5 cycles of work before signalled to stop.