B
B
Berry902020-03-18 15:31:14
Java
Berry90, 2020-03-18 15:31:14

Profit from multithreading on a simple example?

I don’t understand multithreading very well, I sketched the code on threads ( kotlin )

val start = System.currentTimeMillis()

var arrayStart = mutableListOf<String>()
var arrayResult = mutableListOf<String>()
var arrayHelper1 = mutableListOf<String>()
var arrayHelper2 = mutableListOf<String>()


repeat(3_000_000) {
      arrayStart.add((it * 2).toString())
}

val thread1 = Thread(
        Runnable {
            for (i in 0 until arrayStart.size/2-3 step 3) {
                val t = arrayStart.subList(i, i+3)
                arrayHelper1.addAll(0, t.reversed())
            }
        }
    )

val thread2 = Thread(
        Runnable {
            for (i in arrayStart.size/2..arrayStart.size-3 step 3) {
                val t = arrayStart.subList(i, i+3)
                arrayHelper2.addAll(0, t.reversed())
            }
        }
    )

thread1.start()
thread2.start()
thread1.join()
thread2.join()

arrayResult.addAll(arrayHelper1)
arrayResult.addAll(arrayHelper2)

val time = (System.currentTimeMillis() - start) / 1000
println("time: $time")


and code without threads

val start = System.currentTimeMillis()

var arrayStart = mutableListOf<String>()
var arrayResult = mutableListOf<String>()
var arrayHelper1 = mutableListOf<String>()
var arrayHelper2 = mutableListOf<String>()

repeat(3_000_000) {
      arrayStart.add((it * 2).toString())
}

for (i in 0 until arrayStart.size/2-3 step 3) {
      val t = arrayStart.subList(i, i+3)
      arrayHelper1.addAll(0, t.reversed())
}

for (i in arrayStart.size/2..arrayStart .size-3 step 3) {
     val t = arrayStart.subList(i, i+3)
     arrayHelper2.addAll(0, t.reversed())
}

arrayResult.addAll(arrayHelper1)
arrayResult.addAll(arrayHelper2)

val time = (System.currentTimeMillis() - start) / 1000
println("time: $time")


both codes completed in ~300 seconds, how should the code be written so that the difference is visible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2020-03-18
@dimonchik2013

memory watch

M
mayton2019, 2020-03-19
@mayton2019

This is a very dangerous example. It is tied to the garbage collection phase. Warming up the JIT. And the cache size. Depending on the versions of java and OS. And no signor-tomato here will be able to say exactly what transients flow in the 2nd version of the code.
How to rewrite - I do not know. But multithreading is always useful when parsing many sites at the same time. Let the author make a web crawler.

K
koperagen, 2020-03-19
@koperagen

Taking and writing parallel code on threads is not so trivial. Better take the Stream API, with its help, sorting, map-reduce operations and much more are perfectly accelerated by a multiple of the number of cores.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question