Java 知识点

  1. 遍历list列表,两种常用的
java 复制代码
 List<String> list = new ArrayList<>();
        list.add("123");
        list.add("12334");
        for (String a: list) {
            System.out.println(a);
        }
        list.forEach(str -> {
            System.out.println("1" + str);
        });

2 . lambda 表达式,本质 匿名函数

将接口类型和参数类型都省略

java 复制代码
new Thread(new Runnable(){// 接口名
	@Override
	public void run(){// 方法名
		System.out.println("Thread run()");
	}
}).start();

lambda实现

java 复制代码
new Thread(
		() -> System.out.println("Thread run()")// 省略接口名和方法名
).start();

可参照: https://blog.csdn.net/2302_79993788/article/details/140107278

3.HashMap类型定义及遍历

个人不喜欢使用iterator进行遍历

lambda方式

java 复制代码
HashMap<String, String> hash = new HashMap<>();
        hash.put("1", "a");
        hash.put("2", "b");
        hash.put("3", "c");
        hash.forEach(
            (key, value) -> {
                System.out.println(key);
            }
        );

entrySet keySet

java 复制代码
 for(Map.Entry<String, String> a:hash.entrySet()) {
            System.out.println(a.getKey());
            System.out.println(a.getValue());
        }

可参照:https://www.jb51.net/program/314396aog.htm

4.线程创建的几种方式

基于thread

java 复制代码
class MyThread extends Thread{
    @Override
    public void run() {
        while(true){
            System.out.println("Hello t");
            }
        }
    }
    
public class ThreadDemo1 {
    public static void main(String[] args) {
        Thread t=new MyThread();
        //start会创建新的线程
        t.start();
        //run不会创建新的线程,run是在main的线程中执行的
        while(true){
            System.out.println("Hello main");
        }
    }
}

重写Runnable,作为thread参数

java 复制代码
class MyRunnable implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("Hello t");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {//sleep睡眠过程中就将其打断
               // throw new RuntimeException(e);
                e.printStackTrace();
            }
        }
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        MyRunnable runnable=new MyRunnable();
        Thread t=new Thread(runnable);
        t.start();
 
        while(true){
            System.out.println("Hello main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {//sleep睡眠过程中就将其打断
                // throw new RuntimeException(e);
                e.printStackTrace();
            }
        }
    }
 
}

可以转换为lambda写法

java 复制代码
 Thread t=new Thread(() -> {
            while(true){
                System.out.println("Hello t");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {//sleep睡眠过程中就将其打断
                    // throw new RuntimeException(e);
                    e.printStackTrace();
                }
            }
        });

5.队列创建

java 复制代码
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(3); // 创建一个容量为3的BlockingQueue
 
        // 添加元素
        queue.put(1);
        queue.put(2);
        queue.put(3);
 
        // 队列满时,添加操作将阻塞
        // queue.put(4); // 这里会阻塞
 
        // 从队列取元素
        int element1 = queue.take();
        System.out.println(element1); // 输出: 1
 
        // 队列为空时,取元素操作将阻塞
        // int element2 = queue.take(); // 这里会阻塞
 
        // 添加元素,不会阻塞,因为队列还有容量
        queue.offer(4);
 
        // 显示队列中的元素
        while (!queue.isEmpty()) {
            System.out.println(queue.take()); // 输出: 2, 3, 4
        }

6.线程池

newFixedThreadPool: 创建一个固定大小的线程池,适用于控制最大并发数的场景,如果超出了那么就会在队列中等待。

newSingleThreadExecutor: 创建一个单线程化的线程池,只会有一个线程,用于保证所有任务按照指定顺序(FIFO,

LIFO, 优先级)执行的场景。

newScheduledThreadPool: 创建一个定时线程池,用于定时及周期性任务执行的场景。

newCachedThreadPool:

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,否则新建线程;适用于执行大量短期异步任务的场景。

核心是调用ThreadPoolExecutor创建线程池

调用方式:

java 复制代码
 //创建含有5个线程的线程池
    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    //提交5个任务到线程池中
    for (int i = 0; i < 5; i++) {
        final int taskNo = i;
        threadPool.execute(() -> {
            System.out.println("执行任务:"+taskNo);
        });
    }
    //关闭线程池
    threadPool.shutdown();
    //如果线程池还没达到Terminated状态,说明线程池中还有任务没有执行完
    while (!threadPool.isTerminated()) {

    }

需要返回结果的,相当于串行调用

java 复制代码
 ExecutorService threadPool = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            final int taskNo = i;
            Future<Integer> future = threadPool.submit(() -> {
                System.out.println("执行任务:"+taskNo);
                return taskNo;
            });
            System.out.println("处理结果:"+future.get());
        }
        //关闭线程池
        threadPool.shutdown();
        //如果线程池还没达到Terminated状态
        while (!threadPool.isTerminated()) {

        }

自定义拒绝策略

java 复制代码
public class CustomRejectionPolicy implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        // 在这里定义你的自定义处理逻辑
        System.out.println("Task " + r.toString() + " was rejected");
        // 可以选择记录日志、抛出异常、使用备用线程池执行等
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, 2, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(2),
                new CustomRejectionPolicy());

        // 提交任务...
    }
}

可参照: https://blog.csdn.net/who_im_i/article/details/140081175.

可参照:https://blog.csdn.net/qq_47183158/article/details/140931384

7.泛型

java 复制代码
  T :代表一般的任何类。
  E :代表 Element 元素的意思,或者 Exception 异常的意思。
  K :代表 Key 的意思。
  V :代表 Value 的意思,通常与 K 一起配合使用。
  S :代表 Subtype 的意思,文章后面部分会讲解示意。

泛型可应用于:接口、类、方法前 进行修饰

相关推荐
爱编程的鱼31 分钟前
OpenCV Python 绑定:原理与实战
c语言·开发语言·c++·python
这周也會开心38 分钟前
云服务器安装JDK、Tomcat、MySQL
java·服务器·tomcat
hrrrrb2 小时前
【Spring Security】Spring Security 概念
java·数据库·spring
小信丶2 小时前
Spring 中解决 “Could not autowire. There is more than one bean of type“ 错误
java·spring
sdgsdgdsgc2 小时前
Next.js企业级应用开发:SSR、ISR与性能监控方案
开发语言·前端·javascript
周杰伦_Jay3 小时前
【Java虚拟机(JVM)全面解析】从原理到面试实战、JVM故障处理、类加载、内存区域、垃圾回收
java·jvm
rit84324995 小时前
基于MATLAB的模糊图像复原
开发语言·matlab
fie88896 小时前
基于MATLAB的声呐图像特征提取与显示
开发语言·人工智能
程序员小凯6 小时前
Spring Boot测试框架详解
java·spring boot·后端
豐儀麟阁贵6 小时前
基本数据类型
java·算法