5

我尝试了指南中的这段代码:

(defn my-fn [ms]
  (println "entered my-fn")
  (Thread/sleep ms)
  (println "leaving my-fn"))

(let [thread (Thread. #(my-fn 1))]
  (.start thread)
  (println "started thread")
  (while (.isAlive thread)
    (print ".")
    (flush))
  (println "thread stopped"))

当我执行它时,部分输出显示在 REPL 中,另一部分显示在控制台中(因为我通常隐藏它,因为我不使用它,所以它会弹出)。

我想将所有输出发送到 REPL 窗口,我该如何实现?

4

1 回答 1

6

这是因为*out*在新线程中没有绑定到 REPL 编写器。您可以手动绑定它:

(let [thread (let [out *out*] 
               (Thread. #(binding [*out* out] 
                           (my-fn 1))))]
  (.start thread)
  (println "started thread")
  (while (.isAlive thread)
    (print ".")
    (flush))
  (println "thread stopped"))
于 2013-03-04T09:18:48.347 回答