I'm experimenting in Clojure with running independent threads and I'm getting different behaviors I don't understand.
For my code editor I'm using Atom (not emacs), REPL is Chlorine.
I'm testing a really simple function that just prints numbers.
This one prints from 100 to 1 and takes no inputs:
(defn pl100 []
"pl100 = Print Loop from 100 to 1"
(loop [counter 100]
(when (pos? counter)
(do
(Thread/sleep 100)
(println (str "counter: " counter))
(recur (dec counter))))))
This one does the exact same thing, except it takes an input:
(defn pl-n [n]
"pl-n = Print Loop from n to 1"
(loop [counter n]
(when (pos? counter)
(do
(Thread/sleep 100)
(println (str "counter: " counter))
(recur (dec counter))))))
When I use
(.start (Thread. #(.run pl100)))
; --> prints to console REPL
; --> runs with no errors
this code
- prints to the console REPL (where I call lein) and
- runs with no errors
When I use
(.start (Thread. #(.run (pl-n 100))))
; prints to console REPL
; --> java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "target" is null
this code
- prints to the console REPL
- ends with the above exception
When I use
(.start (Thread. pl100))
; --> prints to the console REPL
; --> runs with no errors
this code
- prints to the console REPL
- runs with no errors
When I use
(.start (Thread. (pl-n 100)))
; --> prints to Atom REPL, not console REPL!
; ends with exception
; Execution error (NullPointerException) at java.lang.Thread/<init> (Thread.java:396).
; name cannot be null
; class java.lang.NullPointerException
this code
- prints to the Atom REPL (I'm using Atom, not emacs)! Not to the console REPL like the others
- ends with exception
So, can someone please help me understand:
- Why is it when I'm running a function that takes an input, Java gives an error? Why are the function calls not equivalent?
- What is (.run ...) doing?
- Why is it that sometimes the code prints to the console and other times to Atom/Chlorine?
question from:
https://stackoverflow.com/questions/65852747/clojure-running-multiple-threads-with-functions-with-zero-or-one-input 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…