Java中邪恶的Unsafe,一半天使一半魔鬼-刘宇( 五 )


输出结果:
Counter result:10000000Time passed in ms:466
4、加上原子类型时
package com.test.unsafe;import sun.misc.Unsafe;import java.lang.reflect.Field;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class UnsafeTest {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {//定义线程池ExecutorService executorService = Executors.newFixedThreadPool(1000);Counter counter = new AtomicCounter();//记录开始时间long start = System.currentTimeMillis();//提交1000个任务for (int i=0;i<1000;i++){executorService.submit(new CounterRunnable(counter,10000));}//关闭线程池executorService.shutdown();//等待线程池中任务全部完成 , 最多1个小时executorService.awaitTermination(1, TimeUnit.HOURS);long end = System.currentTimeMillis();System.out.println("Counter result:"+ counter.getCounter());System.out.println("Time passed in ms:"+ (end-start));}interface Counter{void increnment();long getCounter();}static class AtomicCounter implements Counter{private AtomicLong counter = new AtomicLong();public void increnment(){counter.getAndIncrement();}public long getCounter(){return counter.get();}}static class CounterRunnable implements Runnable{private final Counter counter;private final int num;public CounterRunnable(Counter counter, int num) {this.counter = counter;this.num = num;}@Overridepublic void run() {for (int i=0;i
输出结果:
Counter result:10000000Time passed in ms:397
5、通过自定义CAS算法
package com.test.unsafe;import sun.misc.Unsafe;import java.lang.reflect.Field;import java.util.concurrent.Executor;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class UnsafeTest {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {//定义线程池ExecutorService executorService = Executors.newFixedThreadPool(1000);Counter counter = new CasCounter();//记录开始时间long start = System.currentTimeMillis();//提交1000个任务for (int i=0;i<1000;i++){executorService.submit(new CounterRunnable(counter,10000));}//关闭线程池executorService.shutdown();//等待线程池中任务全部完成 , 最多1个小时executorService.awaitTermination(1, TimeUnit.HOURS);long end = System.currentTimeMillis();System.out.println("Counter result:"+ counter.getCounter());System.out.println("Time passed in ms:"+ (end-start));}//获取Unsafe实例private static Unsafe getUnsafe(){Field field = null;Unsafe unsafe = null;try {field = Unsafe.class.getDeclaredField("theUnsafe");field.setAccessible(true);unsafe = (Unsafe) field.get(null);} catch (Exception e) {e.printStackTrace();}return unsafe;}interface Counter{void increnment();long getCounter();}static class CasCounter implements Counter{private volatile long counter = 0;private Unsafe unsafe;private long offset;public CasCounter() throws NoSuchFieldException {this.unsafe = getUnsafe();//根据自身类的变量获取偏移量this.offset = unsafe.objectFieldOffset(CasCounter.class.getDeclaredField("counter"));}public void increnment(){long current = counter;//进行CAS算法比较while(!unsafe.compareAndSwapLong(this,offset,current,current+1)){current = counter;}}public long getCounter(){return counter;}}static class CounterRunnable implements Runnable{private final Counter counter;private final int num;public CounterRunnable(Counter counter, int num) {this.counter = counter;this.num = num;}@Overridepublic void run() {for (int i=0;i