java8新特性
下载jdk地址
https://www.oracle.com/technetwork/java/javase/archive-139210.html
需要登录,选择对对应版本下载安装
windows环境变量配置
添加变量
JAVA_HOME=jdk安装路径
CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar
追加path变量
%JAVA_HOME%\bin
%JAVA_HOME%\jre\bin
Linux环境变量配置
export JAVA_HOME=/usr/local/jdk1.8.0_181-amd64
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
export PATH=$PATH:$JAVA_HOME:$JAVA_HOME/bin
java版本查看
java -version
java安装目录查询
java -verbose, 查看最后一行即为JDK安装路径
线程池
实现Runnable接口、继承Thread类 创建线程方式
Executors 创建线程池工具类
newCachedThreadPool 缓存线程池
newFixedThreadPool 固定线程大小线程池
newSingleThreadExecutor 单线程线程池
newScheduledThreadPool 定时调度线程池
ThreadPoolExecutor 创建线程池类,参数如下
corePoolSize 核心线程数
maximumPoolSize 最大线程数
keepAliveTime 空闲时间
unit 空间时间单位
workQueue 任务队列
threadFactory 线程工厂
handler 线程拒绝策略(4)
AbortPolicy(异常终止,会抛异常,默认策略)
DiscardPolicy(丢弃新任务策略)
DiscardOldestPolicy(丢弃旧任务策略)
CallerRunsPolicy(主线程调用执行)
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue(Integer.MAX_VALUE), new ThreadPoolExecutor.DiscardPolicy());
线程池任务使用示例
List<Callable<Object>> tasks = new ArrayList<>();
for (String str : Arrays.asList(new String[]{"a","b","c"})) {
Callable<Object> task = ()->{
System.out.println(str+":"+Thread.currentThread().getName());
return str;
};
tasks.add(task);
}
ExecutorService threadPool = Executors.newFixedThreadPool(5);
threadPool.invokeAll(tasks, 10, TimeUnit.MINUTES);
threadPool.shutdown();
java自带缓存
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>26.0-jre</version>
</dependency>
Cache<String, Object> caches=CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(5, TimeUnit.MINUTES).build();
刷新机制:包括refresh和expire刷新机制
expireAfterAccess: 当缓存项在指定的时间段内没有被读或写就会被回收。
expireAfterWrite:当缓存项在指定的时间段内没有更新就会被回收。
refreshAfterWrite:当缓存项上一次更新操作之后的多久会被刷新。
锁机制
synchronized(可重入锁、jvm实现)
volatile(禁止指令重排序、保证线程可见性)
ReentrantLock(可重入锁、api实现、lock()、unlock())
ReentrantReadWriteLock(读写锁、不限制读限制写、api实现、readLock()、writeLock())
ReentrantReadWriteLock.WriteLock(lock()、unlock())
ReentrantReadWriteLock.ReadLock(lock()、unlock())
AtomicInteger.cas
wait、notify、notifyAll
AQS (Template Method、AbstractQueuedSynchronizer)
CAS (Unsafe、ABA问题、加版本号、compareAndSet、compareAndSwap)
并发编程
CountDownLatch(N) countDown()、await()
N减为0后,释放await()
等待其他多个任务执行完成后在执行此任务
CyclicBarrier(N, r) await()
await调用N次后执行r方法后释放await()
所有任务都达到某个点后一起执行任务
Semaphore(N) acquire()、release()
对N个资源限制访问,看谁能获取到
ThreadLocal(set、get、数据存储在当前线程)
LockSupport(线程停止、唤醒、park()、unpark(thread))
IO流
InputStream、OutputStream
Reader、Writer
FileInputStream、FileOutputStream
FileReader、FileWriter
ByteArrayInputStream、ByteArrayOutputStream
CharArrayReader、CharArrayWriter
BufferedInputStream、BufferedOutputStream
BufferedReader、BufferedWriter
lambda的几种常用方法
Consumer: 消费型接口,内有抽象方法—void accept(T t)
Supplier: 生产型接口(供给型),内有抽象方法—T get();
Function<T, R>: 函数型接口,内有抽象方法—R apply(T t)
Predicate: 断言型接口,内有抽象方法—boolean test(T t)
Runnable 无参数调用执行
反射
Class cls = Class.forName("com.rbc.Student");
Object obj = cls.newInstance();
Method method = cls.getMethod("hello");
method.invoke(obj);
Person p = new Person();
Class c1 = p.getClass();
Class c2 = Person.class;
Class c3 = Class.forName("com.zhaoss.test02.Person");
ClassLoader loader = Test.class.getClassLoader();
Class c4 = loader.loadClass("com.zhaoss.test02.Person");
Constructor[] c1 = cls.getConstructors();
Constructor[] c2 = cls.getDeclaredConstructors();
Constructor con1 = cls.getConstructor(); 得到无参构造器
Constructor con2 = cls.getConstructor(double.class, double.class);
Constructor con3 = cls.getDeclaredConstructor(int.class);
Object o1 = con1.newInstance();
Object o2 = con2.newInstance(180.5, 170.6);
Field[] fields = cls.getFields();
Field[] declaredFields = cls.getDeclaredFields();
Field score = cls.getField("score");
Field sno = cls.getDeclaredField("sno");
String s = Modifier.toString(sno.getModifiers());
Class clazz = sno.getType();
String typeName = clazz.getName();
String name = sno.getName();
Field sco = cls.getField("score");
Object obj = cls.newInstance();
sco.set(obj,98);
Method[] methods = cls.getMethods();
Method[] declaredMethods = cls.getDeclaredMethods();
Method showInfo1 = cls.getMethod("showInfo");
Method showInfo2 = cls.getMethod("showInfo", int.class, int.class);
Method work = cls.getDeclaredMethod("work",int.class);
System.out.println(work.getName());
int modifiers = work.getModifiers();
System.out.println(Modifier.toString(modifiers));
System.out.println(work.getReturnType());
Class[] parameterTypes = work.getParameterTypes();
Method myMethod = cls.getMethod("myMethod");
Annotation[] annotations = myMethod.getAnnotations();
Class[] exceptionTypes = myMethod.getExceptionTypes();
Object o = cls.newInstance();
myMethod.invoke(o);
showInfo2.invoke(o,12,45)
Class[] interfaces = cls.getInterfaces();
Class superclass = cls.getSuperclass();
Class[] interfaces1 = superclass.getInterfaces();
Package aPackage = cls.getPackage();
System.out.println(aPackage);
System.out.println(aPackage.getName());
Annotation[] annotations = cls.getAnnotations();
正常使用new创建对象,仅在某些地方使用反射会比较方面的统一处理创建对象
虽然提供了反射,并不一定非要使用,仅在某些特定场合使用
RPC调用
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1",8888);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
Class clazz = IUserService.class;
Method method = clazz.getMethod("findUserByID", Integer.class);
String methodName= method.getName();
Class[] parametersTypes = method.getParameterTypes();
Object[] params={1};
objectOutputStream.writeUTF(clazz.getName());
objectOutputStream.writeUTF(methodName);
objectOutputStream.writeObject(parametersTypes);
objectOutputStream.writeObject(params);
objectOutputStream.flush();
ObjectInputStream dataInputStream = new ObjectInputStream(socket.getInputStream());
Object o = dataInputStream.readObject();
objectOutputStream.close();
socket.close();
System.out.println(o);
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
while (true){
Socket socket =serverSocket.accept();
process(socket);
socket.close();
}
}
private static void process(Socket socket) throws Exception{
InputStream inputStream = socket.getInputStream();
OutputStream outputStream= socket.getOutputStream();
ObjectInputStream dataInputStream = new ObjectInputStream(inputStream);
ObjectOutputStream dataOutputStream = new ObjectOutputStream(outputStream);
System.out.println("process");
String clazzName = dataInputStream.readUTF();
String methodName = dataInputStream.readUTF();
Class[] parametersTypes =(Class[]) dataInputStream.readObject();
Object[] args=(Object[]) dataInputStream.readObject();
Class clazz = UserServiceImpl.class;
Method method = clazz.getMethod(methodName,parametersTypes);
User user = (User)method.invoke(clazz.newInstance(),args);
dataOutputStream.writeObject(user);
dataOutputStream.flush();
}
LocalDate
创建LocalDate
LocalDate localDate = LocalDate.now();
localDate.plus
localDate.minus
创建LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now();
localDateTime.plus
localDateTime.minus
LocalDateTime转Date
Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
LocalDate转Date
Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
Date转LocalDateTime
LocalDateTime ldt = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
图片的合成
public class ImageTest {
public static void main(String[] args) throws IOException {
URL url = new URL("");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
BufferedImage bg= ImageIO.read(new File("D://a.png"));
BufferedImage qrCode= ImageIO.read(httpURLConnection.getInputStream());
Graphics2D graphics2d=bg.createGraphics();
int width= qrCode.getWidth()/3;
int height= qrCode.getWidth()/3;
graphics2d.drawImage(qrCode, (bg.getWidth()- width*4/3), (bg.getHeight()-height*4/3), width, height, null);
graphics2d.dispose();
bg.flush();
qrCode.flush();
ImageIO.write(bg,"png", new File("D://f.png"));
}
}
动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Subject {
void action();
}
class RealSubject implements Subject {
publicvoid action() {
System.out.println("我是被代理类,记得要执行我哦!么么~~");
}
}
class MyInvocationHandler implements InvocationHandler {
private Object obj;
public Object blind(Object obj) {
this.obj = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnVal = method.invoke(obj, args);
return returnVal;
}
}
publicclass TestProxy {
public static void main(String[] args) {
RealSubject real = new RealSubject();
MyInvocationHandler handler = new MyInvocationHandler();
Object obj = handler.blind(real);
Subject sub = (Subject)obj;
sub.action();
}
}
注解
@Target: 约束注解的使用范围,可以设置多个
TYPE, 只能注解类,接口
FIELD, 只能注解成员变量
METHOD, 只能注解成员方法
PARAMETER, 只能注解方法参数
CONSTRUCTOR, 只能注解构造器
LOCAL_VARIABLE, 只能注解局部变量
@Retention 约束注解的保留阶段
SOURCE: 注解只作用在源码阶段,生成的字节码文件中不存在
CLASS: 注解作用在源码阶段,字节码文件阶段,运行阶段不存在,默认值
RUNTIME:注解作用在源码阶段,字节码文件阶段,运行阶段(常用)
@Inherited 标记这个注解可被继承,某个类有该注解,则其子类也具有了该注解
@Documented 是否在生成的JavaDoc文档中体现
@Repeatable 是否可以重复标注
示例
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface AnnotationDef {
String value() default "";
}
枚举
public enum Color {
RED, GREEN, BLUE;
}
public enum EnumType {
add(1), update(2);
int type;
EnumType(int type) {
this.type = type;
}
public static EnumType getType(int type) {
for (EnumType enumType : EnumType.values()) {
if (enumType.type == type) {
return enumType;
}
}
return null;
}
}
类加载器
URL url = this.class.getResource("");
URL url = this.class.getResource("/");
URL url = this.class.getClassLoader().getResource("");
URL url = this.class.getClassLoader().getResource("/");
URL url = this.class.getClassLoader().getResource("lib/*.jar");
URLClassLoader loader = new URLClassLoader(new URL[]{url});
Driver driver = (Driver)Class.forName("com.mysqljdbc.Driver", true, loader).newInstance();
String jarDir = System.getProperty("user.dir") +"/lib/*.jar");
URL url = new File(jarDir).toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[]{url});
Driver driver = (Driver)Class.forName("com.mysqljdbc.Driver", true, loader).newInstance();
System.getProperty("user.dir")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)