java怎么关闭channel,Go 关闭 channel 的 close 方法

在 Go 中我们所以 close() 来关闭一个 channel

官方的注释如下

The close built-in function closes a channel, which must be either bidirectional or send-only.

It should be executed only by the sender,never the receiver, and has the effect of shutting down the channel after the last sent value is received.

After the last value has been received from a closed channel c, any receive from c will succeed without blocking, returning the zero value for the channel element.

The form x, ok :=

翻译如下

close 内置函数关闭一个通道,该通道必须是双向的或仅发送的。

如下关闭 ch3 就会报错 invalid operation: close(ch3) (cannot close receive-only channel)

ch1 := make(chan int, 10)

ch2 := make(chan

ch3 := make(

close(ch1)

close(ch2)

close(ch3)

channel 应仅由发送方执行,而不应由接收方执行,并且在收到最后发送的值后具有关闭通道的效果。

即 channel 应该由发送的一方执行,由接收 channel 的一方关闭

func send(ch chan int) {

for i := 0; i < 10; i++ {

ch

}

}

func receive(ch chan int) {

for  {

fmt.Println(

}

close(ch)

}

func main() {

ch := make(chan int, 10)

go send(ch)

go receive(ch)

time.Sleep(1 * time.Millisecond)

}

在从闭合通道 c 接收到最后一个值之后,来自 c 的任何接收都将成功而不会阻塞,返回通道元素的零值。

如下,因为通道元素类型是int,零值是0,所以输出全是ch 的 this is from ch 0 ,而 ch1由于没有赋值,所以没有 IO 操作不能被 select 捕捉

func receive(ch chan int, ch1 chan int) {

for {

select {

case a :=

fmt.Println("this is from ch", a)

case b :=

fmt.Println("this is from ch1", b)

}

}

}

func main() {

ch := make(chan int, 10)

ch1 := make(chan int, 10)

close(ch)

go receive(ch, ch1)

time.Sleep(1 * time.Millisecond)

}

对于封闭的通道,表单x , ok :=

输出 0 和 false ,通过这一点我们可以判断 channel 是否被关闭

ch := make(chan int, 10)

close(ch)

if x, ok :=

fmt.Println(x, ok)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值