A confusion about thread!


#1

Hello everyone,
I am having a bit of problem with thread. It did not work the way I am expecting it to. For example, I have a function like this.

fun doSomething(s: list) {
thread {
while (true) {
sleep(100)
print(“start”)
}
}
thread {
s.forEach {print(it)}
}
}

I expect the string “start” appearing randomly along with the numbers from the list s, but the problem is it waited until all the numbers from s have been printed and then print “start” in the end. What is the problem and how can I overcome it?

Thank you.


#2

I guess printing is really fast, so each element was printed before sleep ended. Maybe try to add a small delay after printing each element.


#3

Well, it sure is faster, but have decrease the sleep time from 100 to 1 and increase the size of the list to 10000000, but still, it only prints the “start” at the beginning and end.


#4

I just tried it using

import java.lang.Thread.sleep
import kotlin.concurrent.*
//sampleStart
fun doSomething(s: List<String>) {
	thread {
		for(i in 0..20) {
			sleep(1000)
			println("start")
		}
	}
	thread {
		s.forEach {print(it); sleep(5)}
	}
}
//sampleEnd
fun main(vararg args: String){
	val list = List(1000){"$it"}
	doSomething(list)
}

and I get an output with “start” in the middle of the numbers as well.