Counter problem

Report a typo

Take a look at a class named Counter:

class Counter {
    var value = 0

    fun increment() {
        value++
    }
}

And another class that extends Thread:

class MyThread(val counter: Counter): Thread() {
    override fun run() {
        counter.increment()
        counter.increment()
        counter.increment()
    }
}

Inside the main function, an instance of Counter is created and incremented twice. After that, counter is passed to the constructor of MyThread to create an instance. Then, the created instance of MyThread is started and the main thread joins it.

// inside the main function

val counter: Counter = Counter()

counter.increment()

counter.increment()

val thread: MyThread = MyThread(counter)

thread.start()

thread.join() // waiting for the thread

val result: Int = counter.value 

The result ...

Select one option from the list
___

Create a free account to access the full topic