package mainimport ( "fmt" "time")func NewTask() { for true { fmt.Println("this is a newtesk goroutine") time.Sleep(time.Second) //延时1 }}func main() { //一定要写在下面的死循环之前 go NewTask()//使用go关键字新建一个协程 for true { fmt.Println("this is a main goroutine") time.Sleep(time.Second) //延时1 } //NewTask()//如果按照这里的写法,这个方法肯定不会被调用到的}
执行的结果
this is a main goroutinethis is a newtesk goroutinethis is a newtesk goroutinethis is a main goroutinethis is a main goroutinethis is a newtesk goroutinethis is a main goroutinethis is a newtesk goroutinethis is a main goroutinethis is a newtesk goroutine///
这里有一点需要注意的是:在一个程序启动时,其主函数即在一个单独的goroutine中运行,我们叫它main goroutine,新的goroutine会用go语句来创建,当主协程(main goroutine)退出时,其它的子协程也会退出,验证一下
package mainimport ( "fmt" "time")func main() { go func() { i := 0 for true { i ++ fmt.Println(" 子协程 i = ", i) time.Sleep(time.Second) } }() i := 0 for true { i ++ fmt.Println(" 主协程 i = ", i) time.Sleep(time.Second) if i == 2{ break } }}
执行结果
主协程 i = 1 子协程 i = 1 主协程 i = 2 子协程 i = 2
被调用的匿名函数是无限循环,当主协程退出时,子协助就算是无限循环也退出了