您好,登錄后才能下訂單哦!
Semaphore,限制對(duì)共享資源訪問的最大線程數(shù)量,要訪問共享資源,需要先申請(qǐng)?jiān)S可,申請(qǐng)到許可才能訪問。訪問結(jié)果了,釋放許可。
線程的調(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ì)被阻塞。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。