golang ---Learn Concurrency

https://github.com/golang/go/wiki/LearnConcurrency

实例1:

package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}

 输出:

world
hello
hello
world
world
hello
hello
world
hello

  可以看到只输出了4个world就退出了,因为main执行完say("hello")就退出了

修改如下:

package main

import (
	"fmt"
	"time"
)

func say(s string) {
	for i := 0; i < 5; i++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Println(s)
	}
}

func main() {
	go say("world")
	var input string
	fmt.Scanln(&input) //程序停止执行,等待用户输入
}

  输出:

world
world
world
world
world
end  //输入的string

  world完整输出了

原文地址:https://www.cnblogs.com/saryli/p/11645912.html