generated from justuser-31/code_projects_template
Выгрузка всех файлов
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package org.example
|
||||
|
||||
var sum: Int = 0
|
||||
var lock: Int = -1
|
||||
var workers: Array<Int> = arrayOf()
|
||||
|
||||
class WorkerThread(private val threadI: Int): Thread() {
|
||||
public override fun run() {
|
||||
for (i in 1..3) {
|
||||
// Wait until unlocked
|
||||
while (lock != threadI) {
|
||||
Thread.sleep(100)
|
||||
}
|
||||
sum += 1
|
||||
println("T$threadI | $sum")
|
||||
Thread.sleep(500)
|
||||
// Pass execution to the next thread
|
||||
// Check if we not last
|
||||
if (workers.size > 1) {
|
||||
// Check if thread last in array
|
||||
if (workers.indexOf(threadI) == (workers.size - 1)) {
|
||||
lock = 0
|
||||
}
|
||||
else {
|
||||
lock = workers.indexOf(threadI) + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun main() {
|
||||
val threadNums = 3;
|
||||
|
||||
var threadArray: Array<Thread> = arrayOf()
|
||||
var firstThread: Boolean = true
|
||||
for (i in 0..<threadNums) {
|
||||
if (firstThread) {
|
||||
lock = i
|
||||
firstThread = false
|
||||
}
|
||||
threadArray += WorkerThread(i)
|
||||
workers += i
|
||||
}
|
||||
for (i in threadArray) {
|
||||
i.start()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user