【发布时间】:2016-11-11 07:44:24
【问题描述】:
我正在尝试在 clojure 中实现用餐哲学家的示例。 由于某些原因,我的程序总是死掉一个例外,说
"java.lang.UnsupportedOperationException: nth 不支持 类型:布尔值"
我无法理解此错误消息,因为我已经尝试从与 nth 完美配合的列表中获取布尔值
我猜错误发生在函数philosopher-thread中的if语句中
控制台打印:
- 3 正在思考
- 1 正在思考
- 4 正在思考
- 0 正在思考
- 2 正在思考
- 0 睡后
- 0 后思考
- 0 交换
- 0 正在吃东西
- 睡后3
- 三思后
代码:
(ns dining-philosphers.core
(:gen-class))
(defn think [n]
(println (str n " is thinking"))
(Thread/sleep (rand 1000))
(println (str n " after sleep"))
)
(defn eat [n]
(println (str n " is eating"))
(Thread/sleep (rand 1000))
)
(def isEating (atom '(false false false false false)))
(defn philosopher-thread [n]
(Thread. #(
(while true (do
(think n)
(println (str n " after think"))
(if (or (nth @isEating (mod (- n 1) 5)) (nth @isEating (mod (+ n 1) 5)))
(println "is waiting for neighbour")
(
do
(println (str n " swap"))
(swap! isEating (fn [l] assoc l n true))
(eat n)
(swap! isEating (fn [l] assoc l n true))
)
)
)
)
)
)
)
(defn -main [& args]
(let [threads (map philosopher-thread (range 5))]
(doseq [thread threads] (.start thread))
(doseq [thread threads] (.join thread))))
【问题讨论】:
标签: clojure clojure-java-interop