可以使用chan与sync.WaitGroup实现java中类似CountDownLatch功能。下面分别使用代码示例来说明。
chan的方式如下:
package main
import (
"time"
"fmt"
"io/ioutil"
)
type Job2 struct {
i int
max int
text string
}
func outputText2(j *Job2, syn chan int) {
fileName := j.text + ".txt"
fileContents := ""
for j.i < j.max {
time.Sleep(1 * time.Millisecond)
fileContents += j.text
fmt.Println(j.text)
j.i++
}
err := ioutil.WriteFile(fileName, []byte(fileContents), 0644)
if err != nil {
panic("something went awry")
}
syn <- 1
}
func main() {
hello := new(Job2)
hello.text = "hello"
hello.i = 0
hello.max = 3
world := new(Job2)
world.text = "world"
world.i = 0
world.max = 5
var syn = make(chan int, 2)
go outputText2(hello, syn)
go outputText2(world, syn)
<-syn
<-syn
fmt.Println("completed over")
//可以有2种同步方式,sync.WaitGroup/chan
}
sync.WaitGroup的实现方式如下:
package main
import (
"time"
"fmt"
"io/ioutil"
"sync"
)
type Job1 struct {
i int
max int
text string
}
func outputText1(j *Job1, wg *sync.WaitGroup) {
defer (*wg).Done()
fileName := j.text + "1.txt"
fileContents := ""
for j.i < j.max {
time.Sleep(1 * time.Millisecond)
fileContents += j.text
fmt.Println(j.text)
j.i++
}
err := ioutil.WriteFile(fileName, []byte(fileContents), 0644)
if err != nil {
panic("something went awry")
}
}
func main() {
//var wg sync.WaitGroup
wg := new(sync.WaitGroup)
hello := new(Job1)
hello.text = "hello"
hello.i = 0
hello.max = 3
world := new(Job1)
world.text = "world"
world.i = 0
world.max = 5
go outputText1(hello, wg)
go outputText1(world, wg)
wg.Add(2)
wg.Wait()
fmt.Println("completed over")
//可以有2种同步方式,sync.WaitGroup/chan
}