Skip to content
Snippets Groups Projects
Commit a53c3744 authored by Matt Bovel's avatar Matt Bovel
Browse files

Add first lecture 6 demos

parent 51fc2d93
No related branches found
No related tags found
No related merge requests found
Pipeline #147681 passed
package lecture6
import java.util.concurrent.ForkJoinPool
// Run using `running lecture6.ExecutorsCreate`.
@main def ExecutorsCreate =
val executor = new ForkJoinPool
executor.execute(new Runnable:
override def run() = log("This task is run asynchronously.")
)
Thread.sleep(500)
package lecture6
import scala.concurrent.ExecutionContext
@main def ExecutionContextCreate =
val ectx = ExecutionContext.global
ectx.execute(new Runnable:
override def run() = log("This task is run asynchronously.")
)
Thread.sleep(500)
package lecture6
import scala.concurrent.ExecutionContext
def execute(body: => Unit) =
ExecutionContext.global.execute(new Runnable:
override def run() = body
)
@main def SimpleExecute =
execute { log("This task is run asynchronously.") }
Thread.sleep(500)
package lecture6
import scala.concurrent.ExecutionContext
import lecture1.thread
class OnePlaceBuffer[Elem]:
var elem: Elem = _
var full = false
def put(e: Elem): Unit = this.synchronized {
while full do wait()
elem = e
full = true
log(f"Put $e in the buffer")
notifyAll()
}
def get(): Elem = this.synchronized {
while !full do wait()
full = false
notifyAll()
log(f"Got $elem from the buffer")
elem
}
@main def OnePlaceBufferDemo =
val buffer = OnePlaceBuffer[Int]()
val getThreads = for i <- 0 until 10 yield thread { buffer.get() }
val putThreads = for i <- 0 until 10 yield thread { buffer.put(i) }
putThreads.foreach(_.join())
getThreads.foreach(_.join())
package lecture6
val log = println(_)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment