如何定义Thread#initialize
?我尝试了以下方法:
(1)
class Thread
def initialize
super
@foo = []
end
end
Thread.new{}.join
(2)
class Thread
def initialize &pr
super(&pr)
@foo = []
end
end
Thread.new{}.join
(3)
class Thread
def initialize
end
end
Thread.new{}.join
但他们返回错误:
Uninitialized thread - check `Thread#initialize'.
答案 0 :(得分:2)
当你以这种方式打开类时,你正在销毁原始的Thread.initialize,对super的调用是Object.initialize,而不是以前Thread.initialize中的内容。
这与此处发生的情况类似:
class Dog
def initialize
puts 'Arf'
end
end
class Dog
def initialize
super
puts 'I did not arf'
end
end
#dog.new "I did not arf"
你可以继承Thread然后使用super,或者你可以使用alias_method
class Thread
alias_method :old_initialize, :initialize
def initialize(*args,&blk)
puts 'Before initialize'
old_initialize(*args,&blk)
end
end