采用java信号量(semaphore)让线程轮流打印
生活随笔
收集整理的這篇文章主要介紹了
采用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)让线程轮流打印的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路由器的硬件测试软件,路由器也跑分?路由
- 下一篇: Android arm64-v8a、ar