java信號量控制線程打印順序的示例分享
import java.util.concurrent.Semaphore;
public class ThreeThread {
public static void main(String[] args) throws InterruptedException {
Semaphore sempA = new Semaphore(1);
Semaphore sempB = new Semaphore(0);
Semaphore sempC = new Semaphore(0);
int N=100;
Thread threadA = new PrintThread(N, sempA, sempB, "A");
Thread threadB = new PrintThread(N, sempB, sempC, "B");
Thread threadC = new PrintThread(N, sempC, sempA, "C");
threadA.start();
threadB.start();
threadC.start();
}
static class PrintThread extends Thread{
int N;
Semaphore curSemp;
Semaphore nextSemp;
String name;
public PrintThread(int n, Semaphore curSemp, Semaphore nextSemp, String name) {
N = n;
this.curSemp = curSemp;
this.nextSemp = nextSemp;
this.name = name;
}
public void run() {
for (int i = 0; i < N; ++i) {
try {
curSemp.acquire();
System.out.println(name);
nextSemp.release();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
相關(guān)文章
mybatis foreach 循環(huán) list(map)實例
這篇文章主要介紹了mybatis foreach 循環(huán) list(map)實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Java基于socket服務(wù)實現(xiàn)UDP協(xié)議的方法
這篇文章主要介紹了Java基于socket服務(wù)實現(xiàn)UDP協(xié)議的方法,通過兩個簡單實例分析了java通過socket實現(xiàn)UDP發(fā)送與接收的技巧,需要的朋友可以參考下2015-05-05
Java中String.split()的最詳細源碼解讀及注意事項
以前經(jīng)常使用String.split()方法,但是從來沒有注意,下面這篇文章主要給大家介紹了關(guān)于Java中String.split()最詳細源碼解讀及注意事項的相關(guān)資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-07-07
BeanUtils.copyProperties復(fù)制對象結(jié)果為空的原因分析
這篇文章主要介紹了BeanUtils.copyProperties復(fù)制對象結(jié)果為空的原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
spring學(xué)習之創(chuàng)建項目 Hello Spring實例代碼
這篇文章主要介紹了spring學(xué)習之創(chuàng)建項目 Hello Spring實例代碼,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Spring加載配置和讀取多個Properties文件的講解
今天小編就為大家分享一篇關(guān)于Spring加載配置和讀取多個Properties文件的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03

