1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| package main
import ( "fmt" "strconv" )
func main() {
var channel chan int fmt.Printf("%T,%v\n", channel, channel) channel = make(chan int) fmt.Printf("%T,%v\n", channel, channel)
go setData(channel) for v := range channel { fmt.Println("读取的数据: ", v) }
var ch1 chan int ch1 = make(chan int) go func() { for i := 0; i < 5; i++ { fmt.Println("子的 goroutine 中,i", i) } ch1 <- 1 fmt.Println("结束") }()
data := <-ch1 fmt.Println("main data --> ", data)
ch2 := make(chan int, 3) fmt.Println(len(ch2), cap(ch2)) ch2 <- 1 ch2 <- 2 ch2 <- 3 fmt.Println(len(ch2), cap(ch2)) ch3 := make(chan string, 3) fmt.Println(len(ch3), cap(ch3)) go setStringData(ch3, 3) for { v, ok := <-ch3 if !ok { fmt.Println("读取完毕", ok) break } fmt.Println("读取的数据是:", v) }
ch4 := make(chan string) isDone := make(chan bool) go SendString(ch4, isDone) data1 := <-ch4 fmt.Println(data1) ch4 <- "learn golang"
<-isDone
singleChanWrite := make(chan<- int) singleChanRead := make(<-chan int)
fmt.Println("main over") }
func setData(ch chan int) { for i := 0; i < 5; i++ { ch <- i } close(ch) }
func setStringData(ch chan string, number int) { for i := 0; i < number; i++ { ch <- strconv.Itoa(i) } close(ch) }
func SendString(ch chan string, isDone chan bool) { ch <- "golang" data2 := <-ch fmt.Println("main goroutine 传来: ", data2)
isDone <- true }
|