package main
import "fmt"
import "runtime"
//go并发程序
func say(s string) {
for i := 0; i < 5; i++ {
runtime.Gosched() //系统让出时间片
fmt.Println(s)
}
}
func main() {
go say("world") //开启一个新的goroutine执行程序
say("hello")
}
//利用channl通信
package main
import "fmt"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum
}
func main() {
a := []int{1, 2, 5, 23}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c
fmt.Println(x, y, x+y)
}
有疑问加站长微信联系(非本文作者)