我想编写一个stressTest (int n, int m)的静态方法,该方法创建n个子流程,这些子流程将m个元素添加到所有子流程之间共享的MySafeList中。如果添加的元素数量与预期的数量(n×m)不同,或者在执行过程中引发异常,则该方法必须返回false。确保测试失败且MySafeList不同步。

然后,我尝试使用静态列表并创建线程表。

import java.util.ArrayList;

class MySafeList extends ArrayList<Double>{

    static ArrayList<Double> mySafeList;

    public boolean add(Double d){
        mySafeList.add(d);
    }

    public int size(){
        return mySafeList.size();
    }

    public Double get(int i){
        mySafeList.get(i);
    }

    static boolean stressTest(int n, int m){
        Thread threads[] = new Thread[n]; //El nombre de tu variable se llama "threads"
        try{
            for(int i=0; i<n; i++){
                threads[i] = new Thread(new ThreadTest(1));
                threads[i].start();
                for(int j=0; j<m;j++){
                    Double d = new Double((double) j);
                    mySafeList.add(d);
                }
            }
        }catch(Exception e){
            return false;
        }
    }

    public static void main(String[] args) {
        MySafeList safeList = new MySafeList();
        stressTest(2,4);
    }

}


但是我得到:

C:\Users\antoi\Documents\Programming\Julien\TD6_multi_threading>javac MySafeList.java
MySafeList.java:9: error: missing return statement
        }
        ^
MySafeList.java:17: error: missing return statement
        }
        ^
MySafeList.java:33: error: missing return statement
        }
        ^
Note: MySafeList.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
3 errors

最佳答案

方法stressTest()是静态的。类变量mySafeList不是。使mySafeList静态,或使方法stressTest()不静态。

另外,mySafeList只能包含Double对象。您试图将int原语添加到mySafeList。您需要将int转换为Double。一种方法是...

Double d = new Double((double) j);

10-07 23:15