package main
import("fmt""time")funcsing(){for i :=0; i <50; i++{
fmt.Println("----正在唱:隔壁泰山----")
time.Sleep(100* time.Millisecond)}}funcdance(){for i :=0; i <50; i++{
fmt.Println("----正在跳舞:赵四街舞----")
time.Sleep(100* time.Millisecond)}}funcmain02(){gosing()dance()}
2.Goroutine 子go程
package main
import("fmt""time")funcmain03(){gofunc(){// 创建一个 子go 程for i :=0; i <5; i++{
fmt.Println("------I'm goroutine -------")
time.Sleep(time.Second)}}()
fmt.Println("------I'm main-------")for i :=0; i <5; i++{// 主 go 程
fmt.Println("------I'm main-------")
time.Sleep(time.Second)if i ==2{break}}}
3.Gosched 让出时间片
package main
import("fmt""runtime")funcmain04(){gofunc(){for{
fmt.Println(" this is goroutine test")}}()for{
runtime.Gosched()// 出让当前 cpu 时间片。
fmt.Println(" this is main test")}}
4.Goexit 结束go程
package main
import("fmt""runtime")functest(){defer fmt.Println("ccccccccccccccccc")//return
runtime.Goexit()// 退出当前go程。defer fmt.Println("ddddddddddddddddd")}funcmain05(){gofunc(){defer fmt.Println("aaaaaaaaaa")test()
fmt.Println("bbbbbbbbbbbbb")}()for{}}
5.GOMAXPROCS CPU核数控制
package main
import("fmt""runtime")funcmain06(){// fmt.Println(runtime.GOROOT())// n := runtime.GOMAXPROCS(0) //将cpu设置为 单核// fmt.Println("n = ", n)
a := runtime.NumCPU()//查询CPU最大核数
fmt.Println(a)
n := runtime.GOMAXPROCS(2)//将cpu设置为 双核
fmt.Println("n = ", n)// n = runtime.GOMAXPROCS(2) //将cpu设置为 双核// fmt.Println("n = ", n)for{go fmt.Print(0)// 子go 程
runtime.Gosched()
fmt.Print(1)// 主 go 程}}