package main import "fmt" import "time" func main() { // ch := make(chan int, 10) ch := make(chan int) go produce("生产者1",ch) go produce("生产者2",ch) time.Sleep(1 * time.Second) go use(ch) time.Sleep(101 * time.Second) } func produce(pname string,ch chan int) { for i:= 0;i < 20;i++ { fmt.Println("produce", pname ," : ", i) ch <- i // 这里需要在打印语句之后,否者可能产生理解歧义 time.Sleep(1 * time.Second) } } func use(ch chan int) { var i int loop1: i = <-ch fmt.Println("use : ",i ) goto loop1 }
以上代码有很多细节上的不完善的地方,修改:
package main import "fmt" import "time" func main() { // ch := make(chan int, 10) ch := make(chan int) defer close(ch) go produce("生产者1",ch) go produce("生产者2",ch) time.Sleep(1 * time.Second) go use(ch) time.Sleep(30 * time.Second) } func produce(pname string,ch chan int) { for i:= 0;i < 20;i++ { fmt.Println("produce", pname ," : ", i) ch <- i time.Sleep(1 * time.Second) } } func use(ch chan int) { for i := range ch { fmt.Println("use : ",i ) } }
多个生产者,多个消费者
package main import "fmt" import "time" func main() { // ch := make(chan int, 10) ch := make(chan int) defer close(ch) go produce("生产者1", ch) go produce("生产者2", ch) time.Sleep(1 * time.Second) go use("消费者1", ch) go use("消费者2", ch) time.Sleep(30 * time.Second) } func produce(pname string, ch chan int) { for i := 0; i < 20; i++ { fmt.Println("produce", pname, " : ", i) ch <- i time.Sleep(1 * time.Second) } } func use(uname string, ch chan int) { for i := range ch { fmt.Println("use", uname, " : ", i) } }
有疑问加站长微信联系(非本文作者)