日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

采用java信号量(semaphore)让线程轮流打印

發布時間:2023/12/20 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 采用java信号量(semaphore)让线程轮流打印 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

semaphore是java.util.concurrent包下的并發工具類。

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the semaphore just keeps a count of the number available and acts accordingly.Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.

大致意思是semaphore可以持有許可證,可以在初始化時指定,執行一次acquire(),獲取一個許可證,線程進入,當許可證為0,則不再允許線程進入,執行一次release釋放一個許可證。

package com.smikevon.concurrent.tools;import java.util.Random; import java.util.concurrent.Semaphore;/*** @description: 有A,B,C三個線程, A線程輸出A, B線程輸出B, C線程輸出C.要求, 同時啟動三個線程, 按順序輸出ABC, 循環10次* @date : 2014年9月17日 下午8:23:05*/ public class TestSemaphore {public static void main(String[] args) {final Semaphore sa = new Semaphore(1);final Semaphore sb = new Semaphore(0);final Semaphore sc = new Semaphore(0);final Random random = new Random(System.currentTimeMillis());new Thread(new Runnable() {public void run() {try {while(true){Thread.sleep(random.nextInt(3000));sa.acquire();doing("A");sb.release();}} catch (InterruptedException e) {e.printStackTrace();}}},"線程a").start();new Thread(new Runnable() {public void run() {try {while(true){Thread.sleep(random.nextInt(3000));sb.acquire();doing("B");sc.release();}} catch (InterruptedException e) {e.printStackTrace();}}},"線程b").start();new Thread(new Runnable() {public void run() {try {while(true){Thread.sleep(random.nextInt(3000));sc.acquire();doing("C");sa.release();}} catch (InterruptedException e) {e.printStackTrace();}}},"線程c").start();}/*** @Description:打印出線程的名字* @param msg* @returType:void*/public static void doing(String msg){System.out.println(Thread.currentThread().getName()+":"+msg);}}

?

轉載于:https://www.cnblogs.com/seanvon/p/4072050.html

總結

以上是生活随笔為你收集整理的采用java信号量(semaphore)让线程轮流打印的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。