Newer
Older
// PDF: https://moodle.epfl.ch/pluginfile.php/3175938/mod_folder/content/0/week01-2-Introduction-to-Threads.pdf
// Video: https://mediaspace.epfl.ch/playlist/dedicated/31866/0_c46icdbx/0_78n7vn4u
// Slides: 6
// In Java (and Scala), we can run a piece of code in a separate thread by
// sub-classing the `Thread` class and overriding the `run` method.
/** Thread counting from 0 to 5.
*
* @param sleepiness
* how long the thread should sleep between loop iterations in milliseconds
*/
class MyThread(val sleepiness: Int) extends Thread:
override def run: Unit =
var i: Int = 0
while i < 6 do
println(getName() + " has counter " + i)
// Run from the SBT shell with `runMain lecture1.javaThreads`.
@main def javaThreads: Unit =
val t1 = MyThread(2)
val t2 = MyThread(3)
println("Little threads did not start yet!")
// Threads are started by explicitly calling the `start` method.
t1.start()
t2.start()
Thread.sleep(4)
println("Parent thread and children are running!")
Thread.sleep(29)
// To wait until a thread terminates, we call its `join` method.