Created
June 24, 2013 06:21
-
-
Save jyfeather/5848062 to your computer and use it in GitHub Desktop.
回调函数的一个简单例子
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# 同步调用、异步调用、回调 | |
# 实例:老大 和 手下,电话联系 | |
class Boss | |
def initialize | |
@phone = 85268744150 | |
@workerA = Worker.new | |
end | |
def callWorker | |
puts "老板:找个手下来帮忙吧" | |
Thread.start do # 异步调用,另起线程找 worker 来工作 | |
@workerA.workForBoss(@phone, self) | |
end | |
puts "老板:我做自己的事..." | |
end | |
def receiveReport # 给 worker 的回调函数 | |
puts "老板:好的,谢谢你完成了任务" | |
end | |
end | |
class Worker | |
def workForBoss(phone, boss) | |
puts "手下:我已经开始工作..." | |
sleep 2 # 手下工作2秒 | |
puts "手下:任务完成,打电话给老板 #{phone}" | |
boss.receiveReport | |
end | |
end | |
Boss.new.callWorker | |
sleep 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
老板:找个手下来帮忙吧 | |
老板:我做自己的事... | |
手下:我已经开始工作... | |
手下:任务完成,打电话给老板 85268744150 | |
老板:好的,谢谢你完成了任务 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment