Contenidos
Ejecución de hilos sin tener en cuenta la concurrencia
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
class ThreadA { fun main() { val b = ThreadB() val c = ThreadC() b.start() c.start() // Esperamos un tiempo para permitir que los hilos completen sus tareas (esto no es seguro en términos de concurrencia) // Thread.sleep(1000) println("Total (Sum): ${b.total}") println("Total (Subtract): ${c.total}") } } class ThreadB : Thread() { var total = 0 override fun run() { for (i in 0 until 1000) { total += i } } } class ThreadC : Thread() { var total = 0 override fun run() { for (i in 0 until 1000) { total -= i } } } fun main() { val threadA = ThreadA() threadA.main() } |
Ejecución de hilos con Synchronized
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class ThreadA { fun main() { val b = ThreadB() val c = ThreadC() b.start() c.start() println("Total (Sum): ${b.total}") println("Total (Subtract): ${c.total}") } } class ThreadB : Thread() { var total = 0 override fun run() { synchronized(this) { for (i in 0 until 100) { total += i } } } } class ThreadC : Thread() { var total = 0 override fun run() { synchronized(this) { for (i in 0 until 100) { total -= i } } } } fun main() { val threadA = ThreadA() threadA.main() } |
Ejecución de hilos con CountDownLatch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.concurrent.CountDownLatch class ThreadA { fun main() { val latch = CountDownLatch(2) // Contador inicializado en 2 val b = ThreadB(latch) val c = ThreadC(latch) b.start() c.start() try { println("Waiting for b and c to complete...") latch.await() } catch (e: InterruptedException) { e.printStackTrace() } println("Total (Sum): ${b.total}") println("Total (Subtract): ${c.total}") } } class ThreadB(private val latch: CountDownLatch) : Thread() { var total = 0 override fun run() { synchronized(this) { for (i in 0 until 100) { total += i } latch.countDown() } } } class ThreadC(private val latch: CountDownLatch) : Thread() { var total = 0 override fun run() { synchronized(this) { for (i in 0 until 100) { total -= i } latch.countDown() } } } fun main() { val threadA = ThreadA() threadA.main() } |