Last active
February 11, 2019 02:43
-
-
Save Pooh3Mobi/78fee64207c939bc324e31378b46c54d to your computer and use it in GitHub Desktop.
Kotlin Parallel performance examples.
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
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
setSupportActionBar(toolbar) | |
fab.setOnClickListener { view -> | |
main() | |
} | |
} | |
} | |
fun main() { | |
Thread { | |
log("many thread start") | |
measureTimeMillis { | |
manyTask1(400) | |
// manyTask2(400) | |
// manyTask3(400) | |
// manyTask4(400) | |
// manyTask5(400) | |
// manyTask6(400) | |
}.also { | |
log("[cost]: ${it}") | |
} | |
}.start() | |
} | |
fun manyTask1(num: Int) { | |
val latch = CountDownLatch(num) | |
(0..num).forEach { _ -> | |
Thread { | |
TimeUnit.MILLISECONDS.sleep(100) | |
latch.countDown() | |
}.start() | |
} | |
latch.await() | |
} | |
fun manyTask2(num: Int) { | |
val latch = CountDownLatch(num) | |
val executor = Executors.newScheduledThreadPool(4) | |
(0..num).forEach { _ -> | |
executor.execute { | |
TimeUnit.MILLISECONDS.sleep(100) | |
latch.countDown() | |
} | |
} | |
latch.await() | |
} | |
fun manyTask3(num: Int) { | |
val latch = CountDownLatch(num) | |
val executor = AsyncTask.THREAD_POOL_EXECUTOR | |
(0..num).forEach { _ -> | |
executor.execute { | |
TimeUnit.MILLISECONDS.sleep(100) | |
latch.countDown() | |
} | |
} | |
latch.await() | |
} | |
fun manyTask4(num: Int) { | |
runBlocking { | |
(0..num).toList().map { | |
suspend { | |
delay(100) | |
} | |
}.forEach { | |
launch(Dispatchers.Unconfined) { | |
withContext(IO) { it() } | |
} | |
} | |
} | |
} | |
fun manyTask6(num: Int) { | |
runBlocking { | |
(0..num).toList().map { | |
suspend { | |
delay(100) | |
} | |
}.forEach { | |
launch(Dispatchers.Default) { | |
withContext(IO) { it() } | |
} | |
} | |
} | |
} | |
fun manyTask5(num: Int) { | |
runBlocking { | |
(0..num).map { | |
async(IO) { | |
suspend { | |
delay(100) | |
}() | |
} | |
}.awaitAll() | |
} | |
} | |
fun log(msg: String) { | |
println("[ababab] $msg") | |
// Log.d("ababab", msg) | |
} |
Author
Pooh3Mobi
commented
Feb 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment