```go
package main
import (
"fmt"
_ "reflect"
"sync"
"time"
)
func writeData(intChan chan int) {
for i := 1; i <= 8000; i++ {
intChan <- i
//fmt.Printf("writeData()写入数据%v", i)
}
close(intChan)
//fmt.Println(intChan)
}
func judgData(intChan chan int, resultChan chan int, exitChan chan bool, done func()) {
defer done()
time.Sleep(time.Millisecond * 1000)
flag := true
//time.Sleep(time.Second *1)
for {
num, ok := <-intChan
if !ok {
fmt.Println("已从intChan读取所有数据")
break
}
for i := 2; i < num; i++ {
if num % i == 0 {
flag = false
break
}
if flag {
resultChan <- num
fmt.Printf("添加%v到resultChan\n", num)
}
}
}
fmt.Println("协程执行完毕")
exitChan <- true
}
func main() {
var wg sync.WaitGroup
intChan := make(chan int, 10000)
resultChan := make(chan int, 20000)
exitChan := make(chan bool, 8)
go writeData(intChan)
for i := 0; i < 8; i++ {
go judgData(intChan, resultChan, exitChan, wg.Done)
}
//go func() {
// for i := 0 ; i < 8 ; i ++ {
// key := <-exitChan
// fmt.Print(key)
// }
// close(resultChan)
//}()
wg.Add(8)
wg.Wait()
close(resultChan)
func() {
for i := 0; i < 8; i++ {
key := <-exitChan
fmt.Printf("key=%v\n", key)
}
}()
for {
res, ok := <-resultChan
if !ok {
break
}
fmt.Printf("素数=%d\n", res)
}
}
```
有疑问加站长微信联系(非本文作者)