天天看点

go最基本生产者与消费

package main

import (
	"fmt"
	"math/rand"
	"time"
)

//生产者
func producer(header string,channel chan<- string)  {
	for{
		channel <- fmt.Sprintf("%s: %v",header,rand.Int31())
		time.Sleep(time.Second)
	}
}

//消费者
func customer(channel <- chan string)  {
	for  {
		message := <- channel
		fmt.Println(message)
	}
}

func main() {
	channel := make(chan string)
	go producer("火柴人",channel)
	go producer("木头人",channel)
	customer(channel)
}