java 线程类不更新属于调用类的共享数组

ndasle7k  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(124)

我试图在leetcode上解决这个问题,但在第19个测试用例超时时卡住了,所以我试图用多线程解决它。
请在下面找到代码:

class Solution {

    public static int[] nums;
    public static int[] answer;
    public static Thread[] threads;

    public int[] productExceptSelf(int[] nums) {

        answer = new int[nums.length];
        threads = new Thread[nums.length];    
        ThreadGroup threadgrp = new ThreadGroup("");
        
        IntStream.range(0, nums.length).forEach(i -> {
        
            threads[i] = new Threaded(threadgrp, i);
            threads[i].start();
        });
        
        while(threadgrp.activeCount() > 0) {
        }

        return answer;

    }
}
class Threaded extends Thread {

    int i;

    Threaded(ThreadGroup obj, int i) {
        this.i = i;
    }

    public void run() {
        answer[i] = getProduct(nums, i);
    }

    public int getProduct(int[] nums, int i) {

        int x = 1;

        for(int j = 0; j < nums.length; j++ ) {

            if(i != j) x = x*nums[j];

        }

        return x;
    }

}

我写的代码,我认为好,但它似乎我得到的输出是0,0,0,0在初始测试用例,这只是答案[]数组初始化的值。测试用例的输入是{1,2,3,4}不知何故,线程无法更新答案[]数组和从nums数组中获取值。我甚至尝试静态。早些时候我使用的是Solution的单例示例。
请协助。
我尝试了不使用线程的方法,它工作得很好,但不够快。然后我创建了一个子类,并尝试使用内部类作为线程。

mf98qq94

mf98qq941#

class Solution {
    
    public int[] productExceptSelf(int[] nums) {
        int[] answer = new int[nums.length];
        Thread[] threads = new Thread[nums.length];    
        ThreadGroup threadgrp = new ThreadGroup("");

        IntStream.range(0, nums.length).forEach(i -> {
            threads[i] = new Thread(new Threaded(nums, answer, i), "Thread " + i);
            threads[i].start();
        });
        
        while(threadgrp.activeCount() > 0){
        
        }
        
        return answer;
    }
}
    
 
class Threaded implements Runnable {
    
    private int[] nums;
    private int[] answer;
    private int i;
    
    Threaded(int[] nums, int[] answer, int i) {
        this.nums = nums;
        this.answer = answer;
        this.i = i;
    }
    
    public void run() {
        answer[i] = getProduct(nums, i);
    }
    
    private int getProduct(int[] nums, int i) {
        int x = 1;  
        for (int j = 0; j < nums.length; j++) {    
            if (i != j) x = x * nums[j];      
        }        
        return x;
    }
}

试试这位前辈

相关问题