defaddOne(): Unit = this.synchronized { TimeUnit.SECONDS.sleep(1) inc += 1 }
defmain(args: Array[String]): Unit = { for (i <- 1 to 10) { newThread { overridedefrun(): Unit = { println(s"run thread with object method $i") addOne() } }.start() } val instance = newSynchronizedDemo for (i <- 1 to 10) { newThread { overridedefrun(): Unit = { println(s"run thread with class method $i") instance.addOne() } }.start() } while (true) { println(s"object inc=$inc, class inc=${instance.inc}") TimeUnit.SECONDS.sleep(1) } }
run thread with class method 7 run thread with class method 4 run thread with object method 8 run thread with object method 7 run thread with class method 10 run thread with class method 8 run thread with class method 9 run thread with object method 5 run thread with object method 3 run thread with object method 2 run thread with object method 4 run thread with object method 10 run thread with object method 9 run thread with class method 5 run thread with class method 3 object inc=0, class inc=0 run thread with object method 1 run thread with class method 6 run thread with class method 1 run thread with class method 2 run thread with object method 6 object inc=1, class inc=1 object inc=2, class inc=2 object inc=3, class inc=2 object inc=4, class inc=4 object inc=5, class inc=5 object inc=6, class inc=6 object inc=7, class inc=7 object inc=8, class inc=8 object inc=9, class inc=9 object inc=10, class inc=10
run thread with object method 2 run thread with object method 1 run thread with object method 3 run thread with object method 4 run thread with object method 5 run thread with object method 6 run thread with object method 7 run thread with object method 8 run thread with object method 9 run thread with object method 10 run thread with class method 1 run thread with class method 2 run thread with class method 3 run thread with class method 4 run thread with class method 5 run thread with class method 6 run thread with class method 7 run thread with class method 8 run thread with class method 9 run thread with class method 10 object inc=0, class inc=0 object inc=1, class inc=0 object inc=1, class inc=1 object inc=1, class inc=2 object inc=1, class inc=3 object inc=1, class inc=4 object inc=1, class inc=5 object inc=1, class inc=6 object inc=1, class inc=7 object inc=1, class inc=8 object inc=1, class inc=9 object inc=1, class inc=10 object inc=2, class inc=10 object inc=3, class inc=10 object inc=4, class inc=10 object inc=5, class inc=10 object inc=6, class inc=10 object inc=7, class inc=10 object inc=8, class inc=10 object inc=9, class inc=10 object inc=10, class inc=10