zoukankan      html  css  js  c++  java
  • go无缓冲通道

    package main
    
    import (
    	"fmt"
    	"math/rand"
    	"sync"
    	"time"
    )
    //wg用来等待程序
    var wg sync.WaitGroup
    
    func init() {
    	//设置随机数种子,加上这行代码,可以保证每次随机都是随机的
    	rand.Seed(time.Now().UnixNano())
    }
    
    func main() {
    	//无缓冲的通道
    	court := make(chan int)
    
    	//计数加2,表示要等待两个goroutine
    	wg.Add(2)
    	go player("Nadal", court)
    	go player("Djokovic", court)
    	//发球
    	court <- 1
    
    	//等待游戏结束
    	wg.Wait()
    
    }
    func player(name string, court chan int) {
    	//在函数退出时调用Done来通知函数工作完成
    	defer wg.Done()
    	for {
    		ball, ok := <-court
    		if !ok {
    			//等待球被击打过来
    			fmt.Printf("Player %s Won
    ",name)
    			return
    		}
    		//选随机数,然后用这个数判断我们是否丢球
    		n := rand.Intn(100)
    		fmt.Printf("n=%d
    ",n)
    		if n%13 == 0 {
    			fmt.Printf("player %s Missed
    ", name)
    			close(court)
    			return
    		}
    		fmt.Printf("Player %s Hit %d
    ", name, ball)
    		ball++
    
    		//将球打向对手
    		court <- ball
    
    	}
    
    }
    
    
  • 相关阅读:
    python设计模式
    tomcat在ubuntu下的配置
    排序算法
    python爬虫(一)
    python实现推荐系统(二)
    python实现k近邻
    python实现逻辑回归
    python实现推荐系统(一)
    SGD实现推荐系统
    pyqt4+chatterbot实现简单聊天机器人程序
  • 原文地址:https://www.cnblogs.com/c-x-a/p/11380993.html
Copyright © 2011-2022 走看看