在Ruby中,线程可以通过Thread类来创建。以下是创建和启动线程的一些建议:
thread = Thread.new do # 在这里编写你的代码 end 或者使用块的方式创建线程:
thread = Thread.new { # 在这里编写你的代码 } 创建线程后,需要调用start方法来启动线程。这将使得线程开始执行。
thread.start 如果你需要等待线程完成执行,可以使用join方法。这将阻塞当前线程,直到被调用的线程完成执行。
thread.join 由于线程的输出默认会混合在一起,因此需要使用一些技巧来区分不同线程的输出。可以使用Thread#join方法来确保线程按照顺序执行,然后使用IO#print或IO#puts方法将输出写入文件或其他IO对象。
output = [] thread1 = Thread.new do output << "Thread 1: Hello, World!" end thread2 = Thread.new do output << "Thread 2: Goodbye, World!" end thread1.join thread2.join puts output.join("\n") 这是一个简单的示例,展示了如何在Ruby中创建和启动线程。你可以根据自己的需求修改代码,以便更好地满足你的应用场景。