Semaphore,限制對(duì)共享資源訪問的最大線程數(shù)量,要訪問共享資源,需要先申請(qǐng)?jiān)S可,申請(qǐng)到許可才能訪問。訪問結(jié)果了,釋放許可。
成都創(chuàng)新互聯(lián)是一家專業(yè)提供巴南企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、H5場(chǎng)景定制、小程序制作等業(yè)務(wù)。10年已為巴南眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。
線程的調(diào)用順序如下:
Thread-1 申請(qǐng)一個(gè)許可,等待幾秒鐘,繼續(xù)執(zhí)行
Thread-2 申請(qǐng)2個(gè)許可,許可不足,阻塞
Thread-3 申請(qǐng)一個(gè)許可,等待幾秒鐘,繼續(xù)執(zhí)行
Thread-1,Thread-3,釋放許可之后,Thread-2可以申請(qǐng)?jiān)S可,成功執(zhí)行。
import java.util.concurrent.Semaphore;
public class Task1 implements Runnable{
private Semaphore semaphore;
public Task1(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "獲取到許可....");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "執(zhí)行....");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "釋放許可....");
semaphore.release();
}
}
}
import java.util.concurrent.Semaphore;
public class Task2 implements Runnable{
private Semaphore semaphore;
public Task2(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "申請(qǐng)?jiān)S可....");
semaphore.acquire(2);
System.out.println(Thread.currentThread().getName() + "獲取到許可....");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "執(zhí)行....");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "釋放許可....");
semaphore.release(2);
}
}
}
import java.text.ParseException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static void main(String[] args) throws ParseException, InterruptedException {
Semaphore semaphore = new Semaphore(2, true);
ReentrantLock lock = new ReentrantLock(true);
Condition condition = lock.newCondition();
Thread t1 = new Thread(new Task1(semaphore),"Thread-1");
t1.start();
Thread.sleep(2000);
Thread t2 = new Thread(new Task2(semaphore),"Thread-2");
Thread t3 = new Thread(new Task1(semaphore),"Thread-3");
t2.start();
t3.start();
}
}
此時(shí),Thread-1申請(qǐng)一個(gè),是足夠的,返回成功,然后持有許可,此時(shí)state=1。
然后執(zhí)行doReleaseShared,設(shè)置頭節(jié)點(diǎn)狀態(tài)為0,準(zhǔn)備喚醒后繼節(jié)點(diǎn),也就是Thread-2.
此時(shí),可能Thread-3還沒有釋放許可,state=1,那么Thread-2又會(huì)被阻塞。