ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > 2018329621186陈魏扬 >
homework-6 Version 0
👤 Author: by 1756894282qqcom 2020-11-03 07:30:35
Semaphore is also an auxiliary class for thread synchronization, which can maintain the number of threads currently accessing itself and provide a synchronization mechanism. Use Semaphore to control the number of threads that access resources at the same time, for example, to achieve the number of concurrent accesses allowed for a file.

Summary of Semaphore's main methods:

void acquire(): Acquire a permit from this semaphore, and block the thread until a permit is provided, otherwise the thread will be interrupted.

void release(): Release a permit and return it to the semaphore.

Int availablePermits(): Returns the number of permits currently available in this semaphore.

boolean hasQueuedThreads(): Query whether there are threads waiting to be acquired.
 1 package com.thread;
2
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5 import java.util.concurrent.Semaphore;
6
7 public class SemaphoreTest {
8 public static void main(String[] args) {
9 ExecutorService service = Executors.newCachedThreadPool();
10 final Semaphore sp = new Semaphore(3);//创建Semaphore信号量,初始化许可大小为3
11 for(int i=0;i<10;i++){
12 try {
13 Thread.sleep(100);
14 } catch (InterruptedException e2) {
15 e2.printStackTrace();
16 }
17 Runnable runnable = new Runnable(){
18 public void run(){
19 try {
20 sp.acquire();//请求获得许可,如果有可获得的许可则继续往下执行,许可数减1。否则进入阻塞状态
21 } catch (InterruptedException e1) {
22 e1.printStackTrace();
23 }
24 System.out.println("线程" + Thread.currentThread().getName() +
25 "进入,当前已有" + (3-sp.availablePermits()) + "个并发");
26 try {
27 Thread.sleep((long)(Math.random()*10000));
28 } catch (InterruptedException e) {
29 e.printStackTrace();
30 }
31 System.out.println("线程" + Thread.currentThread().getName() +
32 "即将离开");
33 sp.release();//释放许可,许可数加1
34 //下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元
35 System.out.println("线程" + Thread.currentThread().getName() +
36 "已离开,当前已有" + (3-sp.availablePermits()) + "个并发");
37 }
38 };
39 service.execute(runnable);
40 }
41 }
42
43 }

Please login to reply. Login

Reversion History

Loading...
No reversions found.