我有一个带有for的程序,它从Arraylist中获取字符串,将它们拆分并发送给Worker类。
工人阶级:
public class WorkerRSR extends SwingWorker<String, Void>{
private static String urlFrames;
private static String urlImg;
public static int bool;
public static int dist;
public static int numI;
public static int spra;
public static boolean isCoda;
public static int numCoda;
public static String algo;
public WorkerRSR(String urlImg, int dist, int numI, int spra, String algo, String urlFrames, boolean isCoda, int numCoda) {
this.urlImg=urlImg;
this.dist=dist;
this.numI=numI;
this.spra=spra;
this.algo=algo;
this.urlFrames=urlFrames;
this.isCoda = isCoda;
this.numCoda = numCoda;
//FIRST CHECK POINT
}
@Override
protected String doInBackground() throws Exception {
PanelRSR_LRSR.getProgessbar().setIndeterminate(true);
go();
return "";
}
@Override
protected void done() {
System.out.println("Algoritmo RSR esguito");
if(isCoda){
CreateOption.codaCont++;
System.out.println("RSR codaCont: "+CreateOption.codaCont);
if(CreateOption.codaCont==CreateOption.csize){
JOptionPane.showMessageDialog(null,"Coda Eseguita", "Attenzione",JOptionPane.WARNING_MESSAGE);
PanelRSR_LRSR.getProgessbar().setIndeterminate(false);
}
}
else{
PanelRSR_LRSR.getProgessbar().setIndeterminate(false);
JOptionPane.showMessageDialog(null,"Finito RSR", "Attenzione",JOptionPane.WARNING_MESSAGE);
}
}
public static void go() throws IOException{
System.out.println("ESEGUO RSR, attendi...");
//SECOND CHECK POINT
System.out.println("RSR n = "+numI+" codaCont: "+CreateOption.codaCont+" numCoda = "+numCoda);
while(true){
if(numCoda==CreateOption.codaCont)
break;
}
MakeRSR m=new MakeRSR();
String name = urlImg.substring(urlImg.lastIndexOf("\\"),urlImg.lastIndexOf("."));
String output=name.substring(1); //?
String urlOutput=urlFrames+"\\finalRSR\\"+name+"-"+algo+"-dist"+dist+"-n"+numI+"-N"+spra+".png";
m.RSR(urlImg,urlOutput,dist,numI,spra);
}
}
问题是这个类会被多次调用,并且每次都会覆盖可变数据的先前值:如果我在第一个检查点检查它们它们是不同的(可能是因为第二次采集必须要进行),但在第二个检查点他们是相同的。 我怎么能让他们保持不同?
答案 0 :(得分:5)
如果这些变量由构造函数设置,则它们不应该是静态的。它们应该是实例变量,因此类的每个实例都可以有不同的值。
public class WorkerRSR extends SwingWorker<String, Void>{
private String urlFrames;
private String urlImg;
private int bool;
private int dist;
private int numI;
private int spra;
private boolean isCoda;
private int numCoda;
private String algo;
public WorkerRSR(String urlImg, int dist, int numI, int spra, String algo, String urlFrames, boolean isCoda, int numCoda) {
this.urlImg=urlImg;
this.dist=dist;
this.numI=numI;
this.spra=spra;
this.algo=algo;
this.urlFrames=urlFrames;
this.isCoda = isCoda;
this.numCoda = numCoda;
//FIRST CHECK POINT
}
...
}
您还应该将所有这些变量更改为私有。如果应该从课外访问它们,则应该通过getter方法访问它们。