package main
import "fmt"
import "math/rand"
import "time"
// producer
func producer(header string, channel chan<- string){
for{
channel <- fmt.Sprintf("%s: %v", header, rand.Int31())
time.Sleep(time.Second)
}
}
// customer
func customer(channel <- chan string){
for{
message:= <-channel
fmt.Println(message)
}
}
func main() {
fmt.Printf("%s\n", "hello world")
channel := make(chan string)
go producer("cat", channel)
go producer("dog", channel)
customer(channel)
}
代碼說明
第3行 導入格式化函數(fmt),隨機數(math/rand),時間(time)包參與編譯
第10行 生產函數,闖入一個標記類型的字符串以及一個只能寫入的通道
第13行 for{}構成一個無限循環
第15行 使用rand.Int31()生成一個隨機數,使用fmt.Sprintf()函數格式化
第18行 使用time.Sleep()函數執行暫停1s再執行這個函數,如果goroutine中執行時,暫停不會影響其他goroutine
第23行 消費者函數,傳入一個只能寫入的通道
第26行 構成一個無限循環
第28行 從通道中取出數據
第31行 將取出來的數據進行打印
第35行 程序入口函數
第37行 實例化一個字符串類型的通道
第39行和第40行 併發執行一個生產者函數,兩行分別創建了這個函數搭配不同參數的兩個goroutine
第42行 執行消費者函數通過通道進行數據消費
運行結果如下
如何理解通道 channel
其實有點像那個水龍頭的水和水管差不多
生產者就是一頭的水
通道就是一根水管負責把水傳輸到另一邊
消費者就是相當我們平時用水一樣需要用桶子把水裝起來一樣