java.util.concurrent
Java本身不可以开启线程
并发编程的原因:充分利用CPU资源
获取当前核数
Runtime.getRuntime().availableProcessors();
6个
wait | sleep |
---|---|
属于Object | 属于Thread |
会释放锁 | 不释放锁 |
在同步代码块中 | 在任意地方 |
lock和synchronized的区别
synchronized lock 内置关键字 Java类 无法判断锁 可判断锁 自动释放锁 手动释放锁 可重入锁,非公平 可重入锁,公平/非公平 适合少量代码 适合大量代码
lock java.util.concurrent.locks
lock三部曲
synchroniazed | Lock |
---|---|
wait | Condition.await |
notify | Condition.signal |
synchronized版
用
if
可能产生虚假唤醒情况,判断等待应写在while
循环中
用if
判断的话,唤醒后线程会从wait
之后的代码开始运行,但是不会重新判断if条件,直接继续运行if
代码块之后的代码,而如果使用while
的话,也会从wait
之后的代码运行,但是唤醒后会重新判断循环条件,如果不成立再执行while
代码块之后的代码块,成立的话继续wait
。
class Data{
private int number = 0;
public synchronized void increment(){
while(number!=0){
//判断
//等待
this.wait();
}
//业务
number++;
//通知其他线程
this.notifyAll();
}
}
-JUC版
class Data{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment(){
lock.lock();
try{
while(number!=0){
//判断
//等待
condition.await();
}
//业务
number++;
//通知其他线程
condition.signalAll();
//conditionX.signal==>唤醒指定的监视器
}catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
public class ReadWriteLockDemo {
public static void main(String[] args) {
MyCacheLock cache = new MyCacheLock();
for (int i = 1; i <= 5; i++) {
int temp = i;
new Thread(() -> {
cache.put(String.valueOf(temp), temp);
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
int temp = i;
new Thread(() -> {
cache.get(String.valueOf(temp));
}, String.valueOf(i)).start();
}
}
}
class MyCacheLock {
private volatile Map<String, Object> map = new HashMap<>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
readWriteLock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "put" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "put done");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public void get(String key) {
readWriteLock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + "get" + key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "get done");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}
class MyCache {
private volatile Map<String, Object> map = new HashMap<>();
public void put(String key, Object value) {
System.out.println(Thread.currentThread().getName() + "put" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "put done");
}
public void get(String key) {
System.out.println(Thread.currentThread().getName() + "get" + key);
Object o = map.get(key);
System.out.println(Thread.currentThread().getName() + "get done");
}
}
public class ListTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 1; i < 10; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString());
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
java.util.ConcurrentModificationException 并发修改异常
解决方案:
Vector默认是安全的 List<String> list = new Vector<>();
用工具类Collections使Arraylist安全 List<String> list = Collections.synchronizedList(new ArrayList<>());
JUC List<String> list = new CopyOnWriteArrayList<>();
CopyOnWrite -> COW写入时复制
CopyOnWriteList对比Vector -> synchronized效率低
Vector
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
CopyOnWriteList
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
public class HasMapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
for (int i = 1; i < 10; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(),UUID.randomUUID().toString());
System.out.println(map);
}, String.valueOf(i)).start();
}
}
}
Collections Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
JUC Map<String, String> map = new ConcurrentHashMap<>();
Runable | Callable |
---|---|
无返回值 | 返回值 |
无异常抛出 | 抛出异常 |
run() | call() |
new Thread()
中只接收Runnable,FutrueTask是Runable的子类,用于适配Callable
传统Runnable
public class RunnableTest {
public static void main(String[] args) {
new Thread(new MyThreadRun(), "Runnable").start();
}
}
class MyThreadRun implements Runnable {
@Override
public void run() {
System.out.println("run()");
}
}
Callable
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyThreadCall callableThread = new MyThreadCall();
FutureTask futureTask = new FutureTask(callableThread);
new Thread(futureTask, "Callable").start();
System.out.println((String) futureTask.get());
}
}
class MyThreadCall implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("call()");
return "call done";
}
}
- get()会产生阻塞 -> 1. 需要等待 2. 使用异步处理
- 结果会被缓存,提高效率->两个线程输出一个结果
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
countDownLatch.countDown();// 计数器减一
}, String.valueOf(i)).start();
}
countDownLatch.await();// 等待计数器归零后向下执行
System.out.println("done");
}
}
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("done");
});
for (int i = 1; i <= 7; i++) {
int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName());
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
信号量
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(6);
for (int i = 1; i <= 12; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "run");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "done");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
- 共享资源互斥时
- 并发限流,控制最大的线程数 -> 安全,高可用
线程池,多线程使用
BlockingDueue双端队列
方式 | 抛异常 | 有返回值,不抛异常 | 阻塞等待 | 超时等待 |
---|---|---|---|---|
添加 | add() | offer() | put() | offer(,) |
移除 | remove() | poll() | take() | poll(,) |
判断队列首 | element() | peek() | - | - |
在队列元素为空的情况下,element() 方法会抛出NoSuchElementException异常,peek() 方法只会返回 null
public static void test1() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("A"));
System.out.println(blockingQueue.add("B"));
System.out.println(blockingQueue.add("C"));
/// java.lang.IllegalStateException: Queue full
//System.out.println(blockingQueue.add("D"));
System.out.println("---");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
/// java.util.NoSuchElementException
//System.out.println(blockingQueue.remove());
}
public static void test2() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("A"));
System.out.println(blockingQueue.offer("B"));
System.out.println(blockingQueue.offer("C"));
//队列满则返回false
System.out.println(blockingQueue.offer("D"));
System.out.println("---");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//无对象则返回null
System.out.println(blockingQueue.poll());
}
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
blockingQueue.put("A");
blockingQueue.put("B");
blockingQueue.put("C");
///队列满则阻塞等待
//blockingQueue.put("D");
System.out.println("---");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
///队列空则阻塞等待
//System.out.println(blockingQueue.take());
}
public static void test4() throws InterruptedException {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("A"));
System.out.println(blockingQueue.offer("B"));
System.out.println(blockingQueue.offer("C"));
//队列满则阻塞等待2s
System.out.println(blockingQueue.offer("D", 2, TimeUnit.SECONDS));
System.out.println("---");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
//队列空则阻塞等待2s
System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
}
public static void test5() {
ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
//为空则返回null
System.out.println(blockingQueue.peek());
//java.util.NoSuchElementException
System.out.println(blockingQueue.element());
}
同步队列
每次put之后必须先take,才可继续put
public class SynchronousQueueTest {
public static void main(String[] args) {
SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>();
new Thread(() -> {
try {
System.out.println(Thread.currentThread().getName() + "put 1");
synchronousQueue.put("1");
System.out.println(Thread.currentThread().getName() + "put 2");
synchronousQueue.put("2");
System.out.println(Thread.currentThread().getName() + "put 3");
synchronousQueue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("T1 over");
}
}, "T1").start();
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + "take " + synchronousQueue.take());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("T2 over");
}
}, "T2").start();
}
}
Executors.newSingleThreadExecutor();
Executors.newFixedThreadPool(5);
Executors.newCachedThreadPool();
int corePoolSize
核心线程池大小int maximumPoolSize
最大核心线程池大小long keepAliveTime
等待超时时间TimeUnit unit
超时单位BlockingQueue<Runnable> workQueue
阻塞队列ThreadFactory threadFactory
线程工厂RejectedExecutionHandler handler
拒绝策略AbortPolicy()
:默认,不处理新的任务且抛出异常CallerRunsPolicy()
:原路返回,返回给请求的线程处理DiscardPolicy()
:队列满了后丢弃任务,不抛异常DiscardOldestPolicy()
:队列满了后,丢弃最老的任务,不抛异常
- 最大线程池大小
- CPU密集型 -> CPU核数
Runtime.getRuntime().availableProcessors();
- IO密集型 -> 判断十分耗IO的线程数
public class PoolDemo1 {
public static void main(String[] args) {
///单线程,最多1个线程
//ExecutorService pool = Executors.newSingleThreadExecutor();
///固定线程,最多n个线程
//ExecutorService pool = Executors.newFixedThreadPool(5);
///可变线程,任意个线程
//ExecutorService pool = Executors.newCachedThreadPool();
//本质都是调用ThreadPoolExecutor
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy()
);
/**
* 1. 核心线程池大小 -> 默认为0
* 2. 最大核心线程池大小 -> 默认为Integer.MAX_VALUE => 会造成OOM
* 3. 等待超时时间
* 4. 超时单位
* 5. 阻塞队列
* 6. 线程工厂(一般不动)
* 7. 拒绝策略
* AbortPolicy() :默认,不处理新的任务且抛出异常
* CallerRunsPolicy() :原路返回,返回给请求的线程处理
* DiscardPolicy() :队列满了后丢弃任务,不抛异常
* DiscardOldestPolicy() :队列满了后,丢弃最老的任务,不抛异常
*/
try {
for (int i = 0; i < 20; i++) {
pool.execute(() -> {
System.out.println(Thread.currentThread().getName()+"done");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.shutdown();
}
}
}
Function 函数型接口
public class FunctionTest1 {
public static void main(String[] args) {
// Function<String, String> function = new Function<String, String>() {
// @Override
// public String apply(String s) {
// return s;
// }
// };
Function<String, String> function = (str) -> {
return str;
};
System.out.println(function.apply("hahaha"));
}
}
Predicate 断定型接口
public class PredicateTest {
public static void main(String[] args) {
// Predicate<String> predicate = new Predicate<String>() {
// @Override
// public boolean test(String s) {
// return s.isEmpty();
// }
// };
Predicate<String> predicate = (s) -> {
return s.isEmpty();
};
System.out.println(predicate.test("hahaha"));
}
}
Consumer 消费型接口
public class ConsumerTest {
public static void main(String[] args) {
// Consumer<String> consumer = new Consumer<String>(){
// @Override
// public void accept(String s) {
// System.out.println(s);
// }
// };
Consumer<String> consumer = (s) -> {
System.out.println(s);
};
consumer.accept("hahaha");
}
}
Supplier 供给型接口
public class SupplierTest {
public static void main(String[] args) {
// Supplier<String> supplier = new Supplier<String>() {
// @Override
// public String get() {
// return "hahaha";
// }
// };
Supplier<String> supplier = () -> {
return "hahaha";
};
System.out.println(supplier.get());
}
}
Predicate断定接口
Function函数型接口
Comparator -> Function函数型接口
Long
Consumer消费型接口
public class StreamTest {
public static void main(String[] args) {
User u1 = new User(1, "a", 20);
User u2 = new User(2, "b", 21);
User u3 = new User(3, "c", 22);
User u4 = new User(4, "d", 23);
User u5 = new User(5, "e", 24);
User u6 = new User(6, "f", 25);
List<User> users = Arrays.asList(u1, u2, u3, u4, u5, u6);
/**
* 1. ID为偶数
* 2. 年龄大于20
* 3. 用户名转大写
* 4. 倒序
* 5. 只输出2个
*/
users.stream()
.filter((u) -> {
return u.getId() % 2 == 0;
})
.filter((u) -> {
return u.getAge() > 20;
})
.map((u) -> {
return u.getName().toUpperCase();
})
.sorted((user1, user2) -> {
return user2.compareTo(user1);
})
.limit(2)
.forEach(System.out::println);
/**
* filter 过滤器,Predicate断定接口
* map 映射,Function函数型接口
* sorted 排序,Comparator -> Function函数型接口
* limit 分页,Long
* forEach 遍历,Consumer消费型接口
*/
}
}
并行执行任务
特点: 任务窃取以双端队列作线程,在任务完成后会从其他队列的尾端抢夺其他的线程的任务
public class ForkJoinTest {
public static void main(String[] args) {
test1();
System.out.println("=====");
try {
test2();
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("=====");
test3();
/*
sum=500000000500000000,用时:330
=====
sum=500000000500000000,用时:294
=====
sum=500000000500000000,用时:219
*/
}
//普通方法
public static void test1() {
long sum = 0L;
long start = System.currentTimeMillis();
for (long i = 1L; i <= 10_0000_0000L; i++) {
sum += i;
}
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + ",用时:" + (end - start));
}
//Forkjoin
public static void test2() throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
ForkJoinPool forkJoinPool = new ForkJoinPool();
ForkJoinTask<Long> forkJoinDemo = new ForkJoinDemo(1L, 10_0000_0000L);
ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinDemo);
long sum = submit.get();
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + ",用时:" + (end - start));
}
//stream
public static void test3() {
long start = System.currentTimeMillis();
long sum = LongStream
.rangeClosed(0L, 10_0000_0000L)
.parallel()
.reduce(0, Long::sum);
long end = System.currentTimeMillis();
System.out.println("sum=" + sum + ",用时:" + (end - start));
}
}
class ForkJoinDemo extends RecursiveTask<Long> {
private final long start;
private final long end;
public ForkJoinDemo(long start, long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
long temp = 10000L;
if ((end - start) < temp) {
long sum = 0L;
for (long i = start; i <= end; i++) {
sum += i;
}
return sum;
} else {
long middle = (start + end) / 2;
ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
task1.fork();
task2.fork();
return task1.join() + task2.join();
}
}
}
Interface Future<V>
CompletableFuture<T>
public class FutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//无返回值
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "runAsync");
});
System.out.println("-----");
completableFuture.get();
System.out.println("============");
//有返回值
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "supplyAsync");
int i = 10 / 0;
return 1024;
});
System.out.println(completableFuture1.whenComplete((t, u) -> {
System.out.println("t=" + t);//正常结果
System.out.println("u=" + u);//错误信息
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return -1;//错误时的结果
}).get());
}
}
java内存模型(概念,模型)
JMM特征
JMM操作
lock (锁定):作用于主内存的变量,把一个变量标识为线程独占状态
unlock (解锁):作用于主内存的变量,它把一个处于锁定状态的变量释放出来,释放后的变量才可以被其他线程锁定
read (读取):作用于主内存变量,它把一个变量的值从主内存传输到线程的工作内存中,以便随后的load动作使用
load (载入):作用于工作内存的变量,它把read操作从主存中变量放入工作内存中
use (使用):作用于工作内存中的变量,它把工作内存中的变量传输给执行引擎,每当虚拟机遇到一个需要使用到变量的值,就会使用到这个指令
assign (赋值):作用于工作内存中的变量,它把一个从执行引擎中接受到的值放入工作内存的变量副本中
store (存储):作用于主内存中的变量,它把一个从工作内存中一个变量的值传送到主内存中,以便后续的write使用
write (写入):作用于主内存中的变量,它把store操作从工作内存中得到的变量的值放入主内存的变量中
JMM的约定
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9TSEyfPP-1606395141515)(images/JMM模型.png)]
主内存对应的是Java堆中的对象实例部分,工作内存对应的是栈中的部分区域,从更底层的来说,主内存对应的是硬件的物理内存,工作内存对应的是寄存器和高速缓存。
Volatile是Java虚拟机提供的轻量级同步机制
volatile
标记的指令前后添加内存屏障(同时实现可见性)指令重排:编译器优化,指令并行,内存系统
public class VolatileTest {
//private static int num = 0;
//private static volatile int num = 0;//加了volatile后,线程可以感知num的变化,但无法保证原子性
private static volatile AtomicInteger num = new AtomicInteger();
/*
1. lock
2. sychronized
3. 使用Atomic类
*/
public static void main(String[] args) {
testVisibility();
System.out.println("======");
testAtomic();
}
static void testVisibility(){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// while (num == 0) {
//
// }
while (num.get()==0){
//AtomicInteger不能直接等于
}
System.out.println("线程感知num值改变");
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//num = 1;
num.set(1);
System.out.println(num);
}
public static void testAtomic(){
for (int i = 0; i < 20; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 1000; j++) {
//num++;
num.getAndIncrement();//AtomicInteger + 1,方法CAS
}
}
});
thread.start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println(num);
}
}
饿汉式单例
//饿汉式单例:在加载时就创建对象,可能会浪费内存
public class HungryManTest {
private HungryManTest() {
System.out.println(Thread.currentThread().getName());
}
private final static HungryManTest HUNGRY_MAN_TEST = new HungryManTest();
public static HungryManTest getInstance(){
return HUNGRY_MAN_TEST;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HungryManTest.getInstance();
}
});
thread.start();
}
}
}
懒汉式单例
package com.checker.singleton;
public class LazyManTest {
private LazyManTest() {
System.out.println(Thread.currentThread().getName());
}
private static volatile LazyManTest lazyManTest;
public static LazyManTest getInstance(){
// if (lazyManTest == null){
// lazyManTest = new LazyManTest();
// }
///使用双重检测模式:DCL懒汉式
if (lazyManTest == null){
synchronized (LazyManTest.class){
if (lazyManTest == null){
lazyManTest = new LazyManTest();
}
}
}
return lazyManTest;
}
public static void main(String[] args) {
//多线程下单例模式失效
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
LazyManTest.getInstance();
}
});
thread.start();
}
}
}
静态内部类
public class StaticInnerTest {
private StaticInnerTest(){
}
public static class InnerClass{
private static final StaticInnerTest staticInnerTest = new StaticInnerTest();
}
//利用静态内部类返回单例对象
public static StaticInnerTest getInstance(){
return InnerClass.staticInnerTest;
}
}
反射破坏单例 与 枚举
public class SingletonAndReflection {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//普通方法获取单例
LazyManTest instance1 = LazyManTest.getInstance();
//用反射破坏单例
Constructor<LazyManTest> declaredConstructor = LazyManTest.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
//通过反射获取的构造器创建单例
LazyManTest instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
/*
解决方法: 在构造方法中,先将class锁住,判断类模板是否存在,存在则抛出异常
破解方法: 所有对象都为反射创建,不加载类模板
解决方法2: 添加一个flag判断,在对象创建的时候判断flag的值
破解方法2: 用反射再获取修改这个flag
最终方法: 用枚举类创建单例
*/
Constructor<EnumSingle> enumSingleConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);
enumSingleConstructor.setAccessible(true);
//报错: 无法通过反射创建枚举对象
EnumSingle instance3 = enumSingleConstructor.newInstance();
System.out.println(instance3);
}
}
enum EnumSingle{
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}
比较并交换
public class CASTest {
//CAS compare and swap
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(10);
System.out.println(atomicInteger);
//如果当前对象值为 expect:10 则将对象设置为 update:11
atomicInteger.compareAndSet(10,12);
System.out.println(atomicInteger);
//CAS自增1,底层为自旋锁
atomicInteger.getAndIncrement();
System.out.println(atomicInteger);
}
}
public class ABATest {
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(10);
AtomicStampedReference<Integer> atomicReference = new AtomicStampedReference<>(10, 0);
new Thread(new Runnable() {
@Override
public void run() {
//获取原本的版本号
int stamp = atomicReference.getStamp();
System.out.println("stamp:" + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("带时间戳");
System.out.println(atomicReference.compareAndSet(10, 100, stamp, stamp + 1));
System.out.println(atomicReference.getReference());
System.out.println("不带时间戳");
System.out.println(atomicInteger.compareAndSet(10, 100));
System.out.println(atomicInteger);
}
}, "T1").start();
new Thread(new Runnable() {
@Override
public void run() {
int stamp = atomicReference.getStamp();
atomicReference.compareAndSet(10, 30, stamp, stamp + 1);
stamp = atomicReference.getStamp();
atomicReference.compareAndSet(30, 10, stamp, stamp + 1);
atomicInteger.compareAndSet(10, 30);
atomicInteger.compareAndSet(30, 10);
}
}, "T2").start();
}
}
int在大小超过-127~127时,会new新的对象,应该用Interger类进行操作
//获取原本的版本号
int stamp = atomicReference.getStamp();
System.out.println(“stamp:” + stamp);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("带时间戳");
System.out.println(atomicReference.compareAndSet(10, 100, stamp, stamp + 1));
System.out.println(atomicReference.getReference());
System.out.println("不带时间戳");
System.out.println(atomicInteger.compareAndSet(10, 100));
System.out.println(atomicInteger);
}
}, "T1").start();
new Thread(new Runnable() {
@Override
public void run() {
int stamp = atomicReference.getStamp();
atomicReference.compareAndSet(10, 30, stamp, stamp + 1);
stamp = atomicReference.getStamp();
atomicReference.compareAndSet(30, 10, stamp, stamp + 1);
atomicInteger.compareAndSet(10, 30);
atomicInteger.compareAndSet(30, 10);
}
}, "T2").start();
}
}
> int在大小超过-127~127时,会new新的对象,应该用Interger类进行操作
文章浏览阅读793次。1. 离散傅立叶变换的 Matlab实现Matlab 函数 fft、fft2 和 fftn 分别可以实现一维、二维和 N 维 DFT 算法;而函数 ifft、ifft2 和 ifftn 则用来计算反 DFT 。这些函数的调用格式如下:A=fft(X,N,DIM)其中,X 表示输入图像;N 表示采样间隔点,如果 X 小于该数值,那么 Matlab 将会对 X 进行零填充,否则将进行截取,使之长度为 ..._matlab中dctmtx用法
文章浏览阅读37次。rm -rf mydir /* 删除mydir目录 */ cd mydir /* 进入mydir目录 */ cd – /* 回上一级目录 */ cd ~ /* 回根目录 */ mv tools tool /* 把tools目录改名为tool */ ln -s tool bac/* 给tool目录创建名为bac的符号链接,最熟悉的应该就是FTP中www链接到public_html目录了...
文章浏览阅读1.2k次。以上是30个常用的思科设备巡检命令,用于获取设备的各种配置和状态信息。在网络设备的日常运维和故障排查中,这些命令可以帮助管理员快速了解设备的状态、配置和性能情况,以便及时发现和解决潜在的问题。今天给大家带来的是30个思科设备巡检的命令,每个命令都有解释,希望对每位网络工程师有所帮助!你好,这里是网络技术联盟站。_思科ac巡检命令
文章浏览阅读2w次。mac电脑触控板快速选择前提:在截图或者选择的时候,点击触控板在拖动会很麻烦,mac提供一个三指拖移的功能,能够用三指快速拖移,这样就变成四指切换。步骤左上角,点击苹果logo,选择系统偏好设置点击辅助功能,选择“鼠标与触控板”点击“触控板选项”,勾选启动拖移,选择“三指拖移”,选择“好”就设置完毕啦。这样,就可以一指滑动,轻触点击;二指滑动三指拖移四指切换面板棒呆..._mac trackpad 两指移动
文章浏览阅读2.2k次。文章目录1 图片被划分为CTU2 图片被划分为SubPicture、Slice、Tile2.1 Tile、SLice、SubPicture的概念2.2 光栅扫描分区模式2.3 矩形分区模式3 CTU以树形继续向下划分3.1 HEVC的划分方式3.2 VVC的划分方式3.3 编解码方式3.4 示例3.5 高层参数及限制3.6 帧内的色度独立划分4 CU在图片边缘的划分5 CU冗余划分的限制6 虚拟管..._h.266 ctb
文章浏览阅读1.5k次。从零开始搭建自己的vue组件库——01创建引言项目创建修改目录结构添加第一个组件以及样式文件夹引言因工作需要,要打造一套属于自己团队的组件库,本人也是第一次接到这种任务,虽然不着急,但是之前从来没做过,因此特意再此记录下过程,也希望自己能坚持下去,当然,过程中少不了查阅各种资料,也会再次记录下各种各样的问题,本组件库的开发基于vue2.0,主要用于pc端,会参考element-ui进行开发项目创建首先第一步是要创建一个vue工程vue create xxxx创建具体流程在这里不再详细说明,创建完_vue构建自己的组件库
文章浏览阅读2.3k次,点赞2次,收藏2次。zhuanzai1.密钥长度rsa算法初始化的时候一般要填入密钥长度,在96-1024bits间(1)为啥下限是96bits(12bytes)?因为加密1byte的明文,需要至少1+11=12bytes的密钥(不懂?看下面的明文长度),低于下限96bits时,一个byte都加密不了,当然没意义啦(2)为啥上限是1024(128bytes)?这是算法本身决定的...当然如果某天网上出_rsa2048原文长度限制
文章浏览阅读1.7k次。llua的源码和php后台源码,功能有,卡密系统,远程公告,远程更新,文件系统,网站默认账号 admin 123456使用方法:wwrgu.lanzouq.com/irLiC061rkhc_网络验证源码
文章浏览阅读3.7k次,点赞2次,收藏14次。目录写在前面SM规范简述安全管理器加密工具配对流程安全属性IO功能加密密钥大小配对算法低功耗蓝牙安全密钥和值的定义分发密钥的生成密钥分配安全管理器会话协议介绍命令格式写在前面安全规范协议,主要是描述LE控制器设备配对、认证、加密等过程进行规定,同时也对相关算法进行了说明。低功耗蓝牙的安全管理经历了几个阶段,LE传统配对方式和安全连接。这篇协议基本上是参考蓝牙核心协v5.0议进行的翻译,并且只选取了我认为重要的部分,如果需要深入详_smp协议
文章浏览阅读98次。计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?编写Demo04MathPractise.java类package com.iflytek.day08.demo04;/*题目:计算在-10.8到5.9之间,绝对值大于6或者小于2.1的整数有多少个?分析:1. 既然已经确定了范围,for循环2. 起点位置-10.8应该转换成为-10,两种办法: 2.1 可以使用Math.ceil方法,向上(向正方向)取整 2.2 强转成为int,自动舍弃所有小数位3_java math计算在 -10.8 到 5.9 之间,绝对值大于 6 或者小于 2.1 的整数有多少个?
文章浏览阅读1.7k次。C++使用随机数_c++suijizhongzi
文章浏览阅读793次。参考地址:http://blog.csdn.net/jj120522/article/details/8075249