package com.thread.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDome {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2,true);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 30; i++) {
executorService.execute(new Thread01(semaphore));
}
// for (int i = 0; i < 3; i++) {
// executorService.execute(new Thread01(semaphore));
// }
// for (int i = 0; i < 20; i++) {
// executorService.execute(new Thread01(semaphore));
// }
executorService.shutdown();
}
static class Thread01 implements Runnable {
Semaphore semaphore;
public Thread01(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "开始执行任务");
System.out.println(semaphore.availablePermits());
TimeUnit.MILLISECONDS.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "任务结束");
semaphore.release();
}
}
static class Thread02 implements Runnable {
Semaphore semaphore;
public Thread02(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "开始执行任务");
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "任务结束");
semaphore.release();
}
}
static class Thread03 implements Runnable {
Semaphore semaphore;
public Thread03(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "开始执行任务");
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "任务结束");
semaphore.release();
}
}
}
Semaphore 的使用
最新推荐文章于 2024-04-10 09:30:00 发布