协程入门案例
# 2. 协程入门案例
【1】案例: 请编写一个程序,完成如下功能: (1)在主线程中,开启一个goroutine,该goroutine每隔1秒输出"hello golang" (2)在主线程中也每隔一秒输出"hello msb",输出10次后,退出程序 (3)要求主线程和goroutine同时执行
package main
import (
"fmt"
"strconv"
"time"
)
func test() {
for i := 1; i <= 10; i++ {
fmt.Println("hello golang" + strconv.Itoa(i))
time.Sleep(time.Second)
}
}
func main() { // main主线程
go test() // go test() 开启协程
for i := 1; i <= 10; i++ {
fmt.Println("hello msb" + strconv.Itoa(i))
time.Sleep(time.Second)
}
}
/*
hello msb1
hello golang1
hello golang2
hello msb2
hello msb3
hello golang3
hello golang4
hello msb4
hello msb5
hello golang5
hello golang6
hello msb6
hello msb7
hello golang7
hello golang8
hello msb8
hello msb9
hello golang9
hello msb10
hello golang10
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
编辑 (opens new window)