1、代码,可以通过Context关闭任务
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx1, cancel1 := context.WithCancel(context.Background())
ctx2, cancel2 := context.WithCancel(context.Background())
ctx3, _ := context.WithCancel(context.Background())
go watch(ctx1, "任务1")
go watch(ctx2, "任务2")
go watch(ctx3, "任务3")
time.Sleep(3 * time.Second)
cancel1()
cancel2()
time.Sleep(3 * time.Second)
}
func watch(ctx context.Context, name string) {
for {
select {
case <-ctx.Done():
fmt.Println(name, "exited..")
return
default:
fmt.Println(name, "runing...")
time.Sleep(2 * time.Second)
}
}
}
2、执行结果
任务3 runing...
任务1 runing...
任务2 runing...
任务3 runing...
任务1 runing...
任务2 runing...
任务1 exited..
任务3 runing...
任务2 exited..
任务3 runing...