低耦合:
虚假唤醒解决办法:if判断改为while循环(官方文档)
减法计数器
加法计数器:
匿名内部类访问局部变量时需要加final修饰(在jdk8之前)
https://blog.csdn.net/tianjindong0804/article/details/81710268?ops_request_misc=&request_id=&biz_id=102&utm_term=%E5%8C%BF%E5%90%8D%E5%B1%80%E9%83%A8%E7%B1%BB%E8%AE%BF%E9%97%AE%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E8%A6%81%E5%8A%A0final&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-81710268.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
pv并发信号量:
读写锁:
阻塞队列
package juc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
public class ArrayBlockQueue {
public static void main(String[] args) throws InterruptedException {
test4();
}
public static void test(){
ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.add("1"));
System.out.println(blockingQueue.add("2"));
System.out.println(blockingQueue.add("3"));
System.out.println("======================");
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
}
public static void test2(){
ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);
System.out.println(blockingQueue.offer("1"));
System.out.println(blockingQueue.offer("2"));
System.out.println(blockingQueue.offer("3"));
System.out.println("======================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
//超时一直等待
public static void test3() throws InterruptedException {
ArrayBlockingQueue blockingQueue=new ArrayBlockingQueue<>(3);
blockingQueue.put("1");
blockingQueue.put("2");
blockingQueue.put("3");
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("1"));
System.out.println(blockingQueue.offer("2"));
System.out.println(blockingQueue.offer("3"));
blockingQueue.offer("4",1, TimeUnit.SECONDS);
System.out.println("======================");
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
}
}
SynchronousQueue:
线程池:
https://blog.csdn.net/dodod2012/article/details/107464723
package juc;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class 线程池 {
public static void main(String[] args) {
//ExecutorService T = Executors.newSingleThreadExecutor();
//ExecutorService T = Executors.newFixedThreadPool(5);
ExecutorService T = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 100; i++) {
T.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
T.shutdown();
}
}
}
package juc;
import java.util.concurrent.*;
public class 线程池 {
public static void main(String[] args) {
//ExecutorService T = Executors.newSingleThreadExecutor();
//ExecutorService T = Executors.newFixedThreadPool(5);
//ExecutorService T = Executors.newCachedThreadPool();
ExecutorService threadPool =new ThreadPoolExecutor(
2,
5,
3,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
try {
for (int i = 0; i < 3; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"ok");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
}
stream流式计算:
比较器接口重写:
https://blog.csdn.net/weixin_37613476/article/details/119249464?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164169908016780265421672%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=164169908016780265421672&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-2-119249464.first_rank_v2_pc_rank_v29&utm_term=compartor%E6%8E%A5%E5%8F%A3%E6%80%8E%E4%B9%88%E9%87%8D%E5%86%99&spm=1018.2226.3001.4187
package juc;
import java.util.Arrays;
import java.util.List;
public class Stream流计算 {
public static void main(String[] args) {
User u1=new User(1,"a",23);
User u2=new User(2,"b",23);
User u3=new User(3,"c",23);
User u4=new User(4,"d",23);
User u5=new User(5,"e",23);
List<User> list = Arrays.asList(u1,u2,u3,u4,u5);
list.stream().filter(user -> {return user.getId()%2==0;}).filter(user -> {return user.getAge()>=23;})
.map(user -> {user.setName(user.getName().toUpperCase());return user;}).limit(1).forEach(System.out::println);
}
}
自定义sorted排序:
https://blog.csdn.net/zhouzhiwengang/article/details/112312266?ops_request_misc=&request_id=&biz_id=102&utm_term=stream%E6%B5%81%E4%B8%AD%E8%87%AA%E5%AE%9A%E4%B9%89sorted&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-2-112312266.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
package juc;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Stream流计算 {
public static void main(String[] args) {
User u1=new User(1,"a",23);
User u2=new User(2,"b",22);
User u3=new User(3,"c",23);
User u4=new User(4,"d",26);
User u5=new User(5,"e",23);
List<User> list = Arrays.asList(u1,u2,u3,u4,u5);
list.stream().filter(user -> {return user.getId()%2==0;}).filter(user -> {return user.getAge()>=2;})
.map(user -> {user.setName(user.getName().toUpperCase());return user;}).sorted(Comparator.comparing(User::getAge).reversed()).limit(3).forEach(System.out::println);
}
}
package juc;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class 异步 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// CompletableFuture voidCompletableFuture = CompletableFuture.runAsync(() -> {
// try {
// TimeUnit.SECONDS.sleep(2);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"void");
// });
// voidCompletableFuture.get();//他会在这里阻塞 这个顺序很重要
// System.out.println("11111");
CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "Integer");
int i=10/0;
return 1024;
});
System.out.println(integerCompletableFuture.whenComplete((t,u)->{
System.out.println(t);
System.out.println(u);
}).exceptionally((e)->{
System.out.println(e.getMessage());
return 233;
}).get()); //拿到最终结果
System.out.println("111111");
}
}
多线程的执行顺序问题:
https://blog.csdn.net/weixin_41799019/article/details/100172513?spm=1001.2101.3001.6650.6&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&utm_relevant_index=8
异步与多线程:
https://blog.csdn.net/kxkxyzyz/article/details/104775488?ops_request_misc=&request_id=&biz_id=102&utm_term=%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%BC%82%E6%AD%A5%E6%97%B6%E5%A6%82%E6%9E%9C%E6%B2%A1%E6%89%A7%E8%A1%8C%E5%AE%8C%E4%BC%9A%E9%98%BB%E5%A1%9E%E5%90%97&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-4-104775488.first_rank_v2_pc_rank_v29&spm=1018.2226.3001.4187
volatile:
1 可见性:
package juc;
import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;
public class JMM {
private volatile static int num=0;
public static void main(String[] args) {
new Thread(()->{
while (num==0){
}
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
num=1;
System.out.println(num);
}
}
2 非原子性:(可以使用lock和synchronized实现 或者使用原子类)
package juc;
public class Volitile {
private volatile static int num;
private synchronized static void add(){
num++;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 100; i1++) {
add();
}
}).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println(num);
}
}
package juc;
import java.util.concurrent.atomic.AtomicInteger;
public class Volitile {
private static AtomicInteger num=new AtomicInteger();
private synchronized static void add(){
num.incrementAndGet();
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(()->{
for (int i1 = 0; i1 < 100; i1++) {
add();
}
}).start();
}
while (Thread.activeCount()>2){ //很关键
Thread.yield();
}
System.out.println(num);
}
}
(防止指令重排 所以要加voliatile,因为不然1 3 2的话 分配空间了但还没完成构造 这个时候多线程b进来 发现lazyman已经有指向了 那么他就直接返回了 但是他没有完成构造 所以 1 2 3 才是最安全的指令顺序)
package juc;
public enum enumsigle {
INSTANCE;
public enumsigle getInstance(){
return INSTANCE;
}
}
class Text{
public static void main(String[] args) {
enumsigle instance=enumsigle.INSTANCE;
enumsigle instance2=enumsigle.INSTANCE;
System.out.println(instance);
System.out.println(instance2);
}
}
package juc;
public class 单例模式Hungury {
private byte[] data1=new byte[1024*1024];
private byte[] data2=new byte[1024*1024];
private byte[] data3=new byte[1024*1024];
private byte[] data4=new byte[1024*1024];
private 单例模式Hungury(){
}
private final static 单例模式Hungury HUNGURY=new 单例模式Hungury();
public static 单例模式Hungury getInstance(){
return HUNGURY;
}
}
package juc;
import javafx.scene.control.Label;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class LazyMan {
//双重锁效率高 不然直接静态方法加锁类锁也许 效率低一些 锁的资源越小越好
// private LazyMan(){
//
// }
// private LazyMan(){
// synchronized (LazyMan.class){
// if(lazyMan!=null){
// throw new RuntimeException("不要试图反射"); //但他可以直接反射创建两个 也可以破解
// }
// }
// }
public static boolean gx=false;
private LazyMan(){
if(gx==false){
gx=true;
}else {
throw new RuntimeException("不要创建两个对象反射");
}
}
private volatile static LazyMan lazyMan;
public static LazyMan getInstance(){
if(lazyMan==null){
synchronized (LazyMan.class){
if(lazyMan==null){
lazyMan=new LazyMan();
}
}
}
return lazyMan;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
//LazyMan instance=LazyMan.getInstance();
Constructor<LazyMan> declared=LazyMan.class.getDeclaredConstructor(null);
declared.setAccessible(true);
Field gx = LazyMan.class.getDeclaredField("gx");
gx.setAccessible(true);
LazyMan instance2=declared.newInstance();
gx.set(instance2,false);
LazyMan instance3=declared.newInstance();
//System.out.println(instance);
System.out.println(instance2);
System.out.println(instance3);
}
}
package juc;
import java.util.concurrent.TimeUnit;
public class 死锁 {
public static void main(String[] args) {
String lock1="lock1";
String lock2="lock2";
new Thread(new Mythread(lock1,lock2)).start();
new Thread(new Mythread(lock2,lock1)).start();
}
}
class Mythread implements Runnable {
String lockA;
String lockB;
public Mythread(String lockA,String lockB){
this.lockA=lockA;
this.lockB=lockB;
}
@Override
public void run() {
synchronized (lockA){
System.out.println("拿到了A字符串"+Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println("拿到了B字符串"+Thread.currentThread().getName());
}
}
}
}