本文共 2171 字,大约阅读时间需要 7 分钟。
单词Semaphore的中文含义是信号、信号系统。此类的主要作用就是限制线程并发的数量,如果不限制线程并发的数量,则cup的资源很快就被耗尽,每个线程执行的任务是相当缓慢,因为cup要把时间片分配给不同的线程对象,而且上下文切换也要耗时,最终造成系统运行效率大幅降低,所以限制并发线程的数量很有必要
public class Service { private Semaphore semaphore = new Semaphore(2); public void testMethod() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis()); Thread.sleep(5000); System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis()); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } }}public class ThreadA extends Thread { private Service service; public ThreadA(Service service) { super(); this.service = service; } @Override public void run() { service.testMethod(); }}public class Run { public static void main(String[] args) { Service service=new Service(); ThreadA a=new ThreadA(service); a.setName("A"); ThreadA b=new ThreadA(service); b.setName("B"); ThreadA c=new ThreadA(service); c.setName("C"); a.start(); b.start(); c.start(); }}
运行效果:
B begin timer=1518577498811A begin timer=1518577498812B end timer=1518577503812C begin timer=1518577503812A end timer=1518577503812C end timer=1518577508812
可以发现,虽然同时打开了三个线程,但是只有两个线程可以并发执行。
类Semaphore可以有效地对并发执行任务的线程数量进行限制,这种功能可以应用在pool池技术中,可以设置同时访问pool池中数据的线程数量。
本实验的功能是同时有若干线程可以访问池中的数据,但同时只有一个线程可以取得数据,使用完毕后再放回池中。
public class ListPool { private int poolMaxSize=3; private int semaphorePermits=5; private Listlist=new ArrayList<>(); private Semaphore concurrencySemaphore=new Semaphore(semaphorePermits); private ReentrantLock lock=new ReentrantLock(); private Condition condition=lock.newCondition(); public ListPool(){ super(); for(int i=0;i
Thread-2 取得值 test1Thread-3 取得值 test2Thread-2 取得值 test1Thread-5 取得值 test1Thread-1 取得值 test1Thread-1 取得值 test1Thread-0 取得值 test3Thread-1 取得值 test1Thread-10 取得值 test3...............
转载地址:http://tqjqi.baihongyu.com/