1、Semaphore类实现限制线程并发数的。
public class Service {
//实现限制线程并发数
//Semaphore类的构造方法传递的参数permists的值如果大于1时,该类并不能保证安全性,因为还有可能会出现多个线程出现共同访问的实例变量,导致出现脏数据的情况。
private Semaphore semaphore = new Semaphore(10);public void testMethod() {
try {// semaphore.acquire(2); 在代码中一共10个许可,每次执行semaphore.acquire(2);代码消耗掉2个,所以同一时间只有5个线程允许执行acquire()和release()之间的代码。
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 ThreadB extends Thread{
private Service service;public ThreadB(Service service) {
super();
this.service = service;
}
@Override
public void run() {
service.testMethod();
}}
public class ThreadC extends Thread{
private Service service;public ThreadC(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");
ThreadB b = new ThreadB(service);
b.setName("B");
ThreadC c = new ThreadC(service);
c.setName("C");
a.start();
b.start();
c.start();
}}