package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("工人%d,开始工作%d \n", id, j)
time.Sleep(time.Second)
fmt.Printf("工人%d,完成工作%d \n", id, j)
results <- j * 2
}
}
func main() {
const number = 5
jobs := make(chan int, number)
results := make(chan int, number)
// 异步执行worker3次
// 先准备
fmt.Println(1)
for w := 1; w <= 3; w++ {
fmt.Println("w", w)
go worker(w, jobs, results)
}
fmt.Println(2)
// 同步执行5次jobs写入
for j := 1; j <= number; j++ {
fmt.Println("j", j)
jobs <- j
}
fmt.Println(3)
close(jobs) // 关闭jobs读写
// 输出异步结果
fmt.Println(4)
for a := 1; a <= number; a++ {
fmt.Println("工作结果:", <-results)
}
fmt.Println(5)
}