什么是反射:基于反射可动态调用某对象实例中对应的方法,访问查看对象的属性等,无需在编写代码时就确定要创建的对象。
反射的实例:
Class action = Class.forName(“类”);
Method method = action.getMethod(“execute”,null);
Object obj = action.newInstance();
Method.invoke(obj,null);
public class ForReflection {
private Map<String,String> caches = new HashMap<>();
public void execute(String message){
String b = this.toString()+message;
caches.put(b,message);
}
}
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Slf4j
public class Demo {
private static final int WARMUP_COUNT = 10700;
private ForReflection testClass = new ForReflection();
private static Method method = null;
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
method = ForReflection.class.getMethod("execute",new Class[]{String.class});
Demo demo = new Demo();
for (int i = 0;i<20;i++){
demo.testDirectCall();
demo.testCacheMethodCall();
demo.testNoCacheMethodCall();
}
long beginTime = System.currentTimeMillis();
demo.testDirectCall();
long endTime = System.currentTimeMillis();
log.info("直接调用消耗的时间:{}",endTime-beginTime);
beginTime = System.currentTimeMillis();
demo.testNoCacheMethodCall();
endTime = System.currentTimeMillis();
log.info("不缓存method消耗的时间:{}",endTime-beginTime);
beginTime = System.currentTimeMillis();
demo.testCacheMethodCall();
endTime = System.currentTimeMillis();
log.info("缓存method消耗的时间:{}",endTime-beginTime);
}
private void testDirectCall() {
for (int i = 0; i < WARMUP_COUNT; i++) {
testClass.execute("hello");
}
}
private void testCacheMethodCall() throws InvocationTargetException, IllegalAccessException {
for (int i = 0; i < WARMUP_COUNT; i++) {
method.invoke(testClass,new Object[]{"hello"});
}
}
private void testNoCacheMethodCall() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
for (int i = 0; i < WARMUP_COUNT; i++) {
Method testMethod= ForReflection.class.getMethod("execute", new Class[]{String.class});
testMethod.invoke(testClass,new Object[]{"hello"});
}
}
}
原子性操作:
private static AtomicInteger count = new AtomicInteger(); public static int getNextId(){ return count.incrementAndGet(); } public static void main(String[] args) throws InterruptedException { Integer num = getNextId(); System.out.println("发的说法"+num); }
CountDownLatch:在日常开发中经常会遇到需要在主线程中开启多个线程去并行执行任务,并且主线程需要等待所有子线程执行完毕后再进行汇总的场景。在CountDownLatch出现之前一般都使用线程的jion 方法来是实现,但join 不够灵活,不能满足不同场景的需要,所以便产生了CountDownLatch。
public class PSGCDirectOldDemo { private static int id = 0; private static AtomicInteger atomicId = new AtomicInteger(); private static CountDownLatch latch = null; public synchronized static int getNextId(){ return ++id; } public static int getNextIdWithAtomic(){ return atomicId.incrementAndGet(); } public static void main(String[] args) throws InterruptedException { latch = new CountDownLatch(50); long beginTime = System.nanoTime(); for (int i = 0; i < 50; i++) { new Thread(new Task(false)).start(); } latch.await(); System.out.println("阻塞的时间:"+(System.nanoTime()-beginTime)); } static class Task implements Runnable{ private boolean isAtomic; public Task(boolean isAtomic){ this.isAtomic = isAtomic; } @Override public void run() { for (int i = 0; i < 1000; i++) { if (isAtomic){ getNextIdWithAtomic(); }else{ getNextId(); } latch.countDown(); } } } }
线程池的队列:
public class ThreadPoolExecutorDemo { final BlockingQueue<Runnable> queue = new SynchronousQueue<>(); //核心线程数 * 最大线程数,存活时间,存活时间单位,队列,线程工厂,拒绝策略 final ThreadPoolExecutor executor = new ThreadPoolExecutor(10,600,30, TimeUnit.SECONDS,queue, Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy()); final AtomicInteger completedTask = new AtomicInteger(0); final AtomicInteger rejectedTask = new AtomicInteger(0); static long beginTime; final int count =1000; public static void main(String[] args) { beginTime = System.currentTimeMillis(); ThreadPoolExecutorDemo demo = new ThreadPoolExecutorDemo(); demo.start(); } public void start(){ CountDownLatch latch = new CountDownLatch(count); CyclicBarrier barrier = new CyclicBarrier(count); for (int i = 0; i < count; i++) { new Thread(new TestThread(latch,barrier)).start(); } try { latch.await(); executor.shutdown(); } catch (InterruptedException e) { e.printStackTrace(); } } class TestThread implements Runnable{ private CountDownLatch latch; private CyclicBarrier barrier; public TestThread(CountDownLatch latch,CyclicBarrier barrier){ this.latch = latch; this.barrier = barrier; } @Override public void run() { try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } try{ executor.execute(new Task(latch)); }catch (Exception e){ latch.countDown(); System.out.println("被拒绝的任务数:"+rejectedTask.incrementAndGet()); } } } class Task implements Runnable{ private CountDownLatch latch; public Task(CountDownLatch latch){ this.latch = latch; } @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("执行的任务数:"+completedTask.incrementAndGet()); System.out.println("任务的耗时数:"+(System.currentTimeMillis()-beginTime)); latch.countDown(); } } }
FutureTask 可用于异步要获取执行结果或取消执行任务的场景,通过传入runnable 或callable 的任务给FutureTask,直接调用其run方法或放入线程池执行,之后可以在外部通过FutureTask的get 异步获取执行结果。FutureTask可以确保即使调用了多次run方法,它都只会执行一次runnable 或callable 任务,或者通过cancel取消FutureTask的执行等。
public class ThreadPoolExecutorDemo { Map<String, Connection> connectionPool = new HashMap<>(); ReentrantLock lock = new ReentrantLock(); public Connection getConnection(String key){ try{ lock.lock(); if (connectionPool.containsKey(key)){ return connectionPool.get(key); } Connection connection = null; connectionPool.put(key,connection); return connection; }finally { lock.unlock(); } } }