Kotlin协程runBlocking并发launch,Semaphore同步1个launch任务运行
<dependency><groupId>org.jetbrains.kotlinx</groupId><artifactId>kotlinx-coroutines-core</artifactId><version>1.7.3</version><type>pom</type></dependency>
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Semaphore
import java.util.Collectionsvar seq = 0
const val times = 5fun main(args: Array<String>) {val size = 5 //初始容量var ml: MutableList<Int> = ArrayList(size)var data = Collections.synchronizedList(ml)val semaphore = Semaphore(1) //只有1个任务在并发环境中得到授权许可投入运行。runBlocking {launch(Dispatchers.IO) {repeat(Int.MAX_VALUE) {semaphore.acquire()myTask("A", data)semaphore.release()}}launch(Dispatchers.IO) {repeat(Int.MAX_VALUE) {semaphore.acquire()myTask("B", data)semaphore.release()}}launch(Dispatchers.IO) {repeat(Int.MAX_VALUE) {semaphore.acquire()myTask("C", data)semaphore.release()}}}
}//我们希望这块代码在并发环境中不受干扰的完整跑完。
//且每轮都完整、顺序依次输出 0,1,2,3,4
fun myTask(id: String, data: MutableList<Int>) {repeat(times) {data.add(seq++)}println("$id $data")data.clear()seq = 0
}
需要注意,由于Kotlin与Java语言特性的细微差异,虽然同为Semaphore,上述代码如果引入的是 java.util.concurrent.Semaphore ,功能也能正常完成,但运行出来的结果会有小差异。Java版Semaphore会使某条线程较长时间独占CPU轮片,然后再让渡出去CPU,输出的表现就是A或B或C一大片一大片输出后才会换别的任务切入;而Kotlin版Semaphore相对更均匀的切换线程任务轮片,使得A、B、C每个任务如上图那样依次轮番运行。
新Java线程Semaphore:并行环境下访问竞争资源控制_zhangphil的博客-CSDN博客新Java线程Semaphore:并行环境下访问竞争资源控制Semaphore是从Java 1.5引入的Java线程新内容。Semaphore实现在线程的竞争资源访问环境下,对资源的访问控制。只有申请(acquire)得到Semaphore的许可证的线程任务可以访问竞争资源。例如: private void test() { // 虽然有很多线程想访问某些资源,但...https://blog.csdn.net/zhangphil/article/details/83410270Java线程同步可重入锁ReentrantLock与Condition_zhangphil的博客-CSDN博客import java.util.LinkedList;import java.util.Queue;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Main { private Queue...https://blog.csdn.net/zhangphil/article/details/92814997
Java线程同步锁ReentrantLock和Condition中断等待程序前提条件满足_zhangphil的博客-CSDN博客import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;/** * ReentrantLock的lock和unlock必须成对使用且把需要同步的代码块包裹起来。 * lock-unlo...https://blog.csdn.net/zhangphil/article/details/92826986
Java线程同步与阻塞ReentrantLock - Condition替换wait - notify_reentrantlock和wait notify_zhangphil的博客-CSDN博客import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Main { private ReentrantLock lock = new ReentrantLock(false); private Condition con..._reentrantlock和wait notifyhttps://blog.csdn.net/zhangphil/article/details/96360104