在Java中跨线程存储String数组可以使用线程安全的数据结构,如ConcurrentLinkedQueue或CopyOnWriteArrayList。

使用ConcurrentLinkedQueue:

ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

// 线程1
Thread thread1 = new Thread(() -> {
    String[] arr = {"String1", "String2", "String3"};
    for (String str : arr) {
        queue.offer(str);
    }
});

// 线程2
Thread thread2 = new Thread(() -> {
    while (!queue.isEmpty()) {
        String str = queue.poll();
        // 处理str
    }
});

thread1.start();
thread2.start();

使用CopyOnWriteArrayList:

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

// 线程1
Thread thread1 = new Thread(() -> {
    String[] arr = {"String1", "String2", "String3"};
    for (String str : arr) {
        list.add(str);
    }
});

// 线程2
Thread thread2 = new Thread(() -> {
    for (String str : list) {
        // 处理str
    }
});

thread1.start();
thread2.start();

这两种数据结构都是线程安全的,可以在多个线程之间安全地存储和访问String数组

java 跨线程存储String数组

原文地址: https://www.cveoy.top/t/topic/iwjd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录