Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save BUNotesAI/c8bcebaa1f7ddadd59178fa2701ce098 to your computer and use it in GitHub Desktop.

Select an option

Save BUNotesAI/c8bcebaa1f7ddadd59178fa2701ce098 to your computer and use it in GitHub Desktop.
Executor线程池多次执行方法: 测试atom计数器

Executor线程池多次执行方法: 测试atom计数器

;;
;;Executor线程池多次执行方法
;;
(import 'java.util.concurrent.Executors)
(def thread-pool (Executors/newFixedThreadPool (+ 2 (.availableProcessors (Runtime/getRuntime)))))
(defn dothreads! [f & {thread-count :threads
exec-count :times
:or {thread-count 1 exec-count 1}}]
(dotimes [t thread-count]
(.submit thread-pool #(dotimes [c exec-count] (f c)))))
;; executor test with hello method.
(defn hello [name]
(println "Hello " name))
;; 方法执行 8次
(dothreads! hello :threads 2 :times 4)
;; atom 计时器
;;
(def counter (atom 0))
(defn counterplus [] (swap! counter inc))
;; 这里的f后面不能有参数
(defn dothreads! [f & {thread-count :threads
exec-count :times
:or {thread-count 1 exec-count 1}}]
(dotimes [t thread-count]
(.submit thread-pool #(dotimes [c exec-count] (f)))))
(dothreads! counterplus :threads 1000 :times 100)
;; @counter
;; 100000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment