Skip to content
Snippets Groups Projects
01-javaThreads.scala 1.2 KiB
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
package lecture1

// 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
  */
Matt Bovel's avatar
Matt Bovel committed
class MyThread(val sleepiness: Int) extends Thread:
  override def run: Unit =
    var i: Int = 0
    while i < 6 do
      println(getName() + " has counter " + i)
Matt Bovel's avatar
Matt Bovel committed
      i = i + 1
      Thread.sleep(sleepiness)

// Run from the SBT shell with `runMain lecture1.javaThreads`.
@main def javaThreads: Unit =
Matt Bovel's avatar
Matt Bovel committed
  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()
Matt Bovel's avatar
Matt Bovel committed
  Thread.sleep(4)
  println("Parent thread and children are running!")
  Thread.sleep(29)
  // To wait until a thread terminates, we call its `join` method.
Matt Bovel's avatar
Matt Bovel committed
  t1.join()
  t2.join()
  println("Main thread ending.")