You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java多线程执行结果异常:无法获取正确线程数据求助

问题分析与解决方案

核心问题

你在WeddingCard的run()方法里重新创建了全新的Venue和Distribution对象,而非使用主线程中已经被t1、t2线程执行过的实例。这直接导致:

  • 新创建的Venue对象未执行run()方法添加元素,列表为空
  • 新创建的Distribution对象的totalPersons未被赋值,保持默认值0

修复方案

需要把主线程中已初始化并执行完成的Venue和Distribution实例传递给WeddingCard,而非在其内部重新创建。具体修改如下:

1. 修改WeddingCard类

package multithreading.marriageexp;

import java.util.List;

public class WeddingCard implements Runnable{
    // 新增成员变量存储外部传递的实例
    private final Venue venueInstance;
    private final Distribution distributionInstance;

    // 构造方法接收外部实例
    public WeddingCard(Venue venue, Distribution distribution) {
        this.venueInstance = venue;
        this.distributionInstance = distribution;
    }

    @Override
    public void run(){
        System.out.println("Below is the details for the Weddings: ");

        System.out.println("Planned Venues to be picked from::");
        // 使用传递过来的Venue实例
        List<String> venuesList = venueInstance.getVenue();
        venuesList.forEach(x -> System.out.print(x + " "));

        // 使用传递过来的Distribution实例
        System.out.println("\nAnd Total guests:: "+ distributionInstance.getTotalPersons());
    }
}

2. 修改主线程中WeddingCard的初始化逻辑

class WeedingResult{
    public static void main(String[] args) throws InterruptedException{

        Venue venue = new Venue();
        Thread t1 = new Thread(venue);

        Distribution distribution = new Distribution();
        Thread t2 = new Thread(distribution);

        t1.start();
        t1.join();

        t2.start();
        t2.join();

        // 将已执行完成的实例传入WeddingCard
        WeddingCard weddingCard = new WeddingCard(venue, distribution);
        Thread t3 = new Thread(weddingCard);

        t3.start();
        t3.join();

        System.out.println("--------------End of main Thread.--------------------");
    }
}

额外优化建议

  • 为保证多线程环境下的变量可见性,给Venue的venue列表和Distribution的totalPersons添加volatile关键字,避免线程缓存旧值。
  • 可以使用线程安全集合(如CopyOnWriteArrayList)替代ArrayList,当前执行顺序下无问题,但能养成更规范的多线程编码习惯。

内容的提问来源于stack exchange,提问作者Chandan mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:44:52