Executor线程池多次执行方法: 测试atom计数器
Last active
April 11, 2018 05:34
-
-
Save BUNotesAI/c8bcebaa1f7ddadd59178fa2701ce098 to your computer and use it in GitHub Desktop.
Executor线程池多次执行方法: 测试atom计数器
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; | |
| ;;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