scp1: finish task 3

This commit is contained in:
2025-10-14 14:56:12 +02:00
parent c9f24021b6
commit 48803df9cd
2 changed files with 56 additions and 0 deletions

View File

@@ -43,3 +43,7 @@ def quadratic(a: Double, b: Double, c: Double): Option[(Double, Double)] =
// task 2 a)
def polynomial(a: Double, b: Double, c: Double): Double => Double =
(x: Double) => a * x * x + b * x + c
// task 3 a)
def initialize_thread(execute: () => Unit): Thread =
new Thread { override def run = execute() }

View File

@@ -0,0 +1,52 @@
package example
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration.Duration
object ConcurrencyTroubles {
private var value1: Int = 1000
private var value2: Int = 0
private var sum: Int = 0
def moveOneUnit(): Unit = {
value1 -= 1
value2 += 1
if (value1 == 0) {
value1 = 1000
value2 = 0
}
}
def updateSum(): Unit = {
sum = value1 + value2
}
def execute(): Unit = {
while (true) {
this.synchronized {
moveOneUnit()
updateSum()
}
Thread.sleep(50)
}
}
// This is the "main" method, the entry point of execution.
// It could have been placed in a different file.
def main(args: Array[String]): Unit = {
for (i <- 1 to 2) {
val thread = new Thread {
override def run = execute()
}
thread.start()
}
while (true) {
updateSum()
println(sum + " [" + value1 + " " + value2 + "]")
Thread.sleep(100)
}
}
}