foxlog
3/28/2018 - 3:55 AM

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