How to translate java runnable example to clojure

I am a bit confused as to how to translate the Runnable block from this example:

http://www.codejava.net/coding/capture-and-record-sound-into-wav-file-with-java-sound-api

    Thread stopper = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(RECORD_TIME);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            recorder.finish();
        }
    });

The bit of code I'm confused with is this:

   Runnable(){... public void run() {... }}
+4
source share
3 answers

It should be noted that clojure functions implement Runnable.

user=> (ancestors clojure.lang.AFn)
#{clojure.lang.IFn
  java.lang.Object
  java.lang.Runnable
  java.util.concurrent.Callable}

So you can pass fn directly to the constructor Thread.

(def stopper 
  (Thread.
    (fn []
      (try
        (Thread/sleep RECORD_TIME)
        (catch InterruptedException e
          (.printStackTrace e))))))
+8
source

Perhaps through the future :

(def recorder ( /*...*/) )
(def recorded (future (Thread/sleep RECORD_TIME)  (.finish recorder) recorder))

Then find him:

@recorded 
+4
source

, , (java.lang.Runnable ). reify.

(reify java.lang.Runnable
  (run [this]
       (try
         (Thread/sleep RECORD_TIME))
         (catch InterruptedException e
           (.printStackTrace e))))))

Of course, if you just want to execute a set of expressions in a separate thread that you want to use, for example. (future), as mentioned above by roberman.

+2
source

Source: https://habr.com/ru/post/1531717/


All Articles