您好,登錄后才能下訂單哦!
Semaphore,限制對共享資源訪問的最大線程數量,要訪問共享資源,需要先申請許可,申請到許可才能訪問。訪問結果了,釋放許可。
線程的調用順序如下:
Thread-1 申請一個許可,等待幾秒鐘,繼續執行
Thread-2 申請2個許可,許可不足,阻塞
Thread-3 申請一個許可,等待幾秒鐘,繼續執行
Thread-1,Thread-3,釋放許可之后,Thread-2可以申請許可,成功執行。
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() + "執行....");
} 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() + "申請許可....");
semaphore.acquire(2);
System.out.println(Thread.currentThread().getName() + "獲取到許可....");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "執行....");
} 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();
}
}
此時,Thread-1申請一個,是足夠的,返回成功,然后持有許可,此時state=1。
然后執行doReleaseShared,設置頭節點狀態為0,準備喚醒后繼節點,也就是Thread-2.
此時,可能Thread-3還沒有釋放許可,state=1,那么Thread-2又會被阻塞。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。