问题是这样的。我需要多次处理一个大文件。所以我认为线程会帮助我增加时间。到目前为止,我已经完成了这个
实现Runnable
的类:
public class ProcessFile() implements Runnable {
private int max;
private int i;
private int j;
public ProcessFile(int i, int j) {
this.i = i;
this.j = j;
}
public void run() {
//Perform operations on the file
}
public int getMaximum() {
return this.max;
}
}
和我调用线程的类:
public calss Start {
public static void main(String[] args) {
for (int i=0;i<=10;i++) {
for (int j=0;j<=5;j++) {
ProcessFile pf = new ProcessFile(i,j);
new Thread(pf).start();
int maximum = pf.getMaximum();
if (max > currentNr)
System.out.println("max is = " + max);
}
}
}
}
在上面的代码中,我打算每次从文本文件计算最大值,然后在主程序中将其返回,然后处理该值。 上面的代码似乎不起作用,因为没有显示任何值。
EDIT。由于我在第二个循环中创建线程,我想创建5个线程。它们中的每一个都对文件执行相同的操作,但条件不同。此外,每个线程都应该返回一个值,该值应该在创建线程的方法中一次处理一个。
答案 0 :(得分:3)
您必须等待线程完成作业。在这里运行一个线程,然后立即在主线程中调用pf.getMaximum()。
我建议使用java.util.concurrent.Future来获取线程执行的结果,并使用Executors框架来创建线程。
您还可以在每个线程上使用Thread.join(),然后在所有线程完成后检查结果。
<强>更新强>
如果您不想进行任何重大更改,请如何处理?
runnable:
public class ProcessFile implements Runnable {
private ProcessFileListener listener;
private int max;
private int i;
private int j;
public ProcessFile(ProcessFileListener listener, int i, int j) {
this.i = i;
this.j = j;
this.listener = listener;
}
public void run() {
//Perform operations on the file
listener.done(this);
}
public int getMaximum() {
return this.max;
}
}
听众:
public interface ProcessFileListener {
void done(ProcessFile process);
}
主要:
public class Start implements ProcessFileListener {
private int max = Integer.MIN_VALUE;
@Override
public synchronized void done(ProcessFile pf) {
int maximum = pf.getMaximum();
if (maximum > max) {
max = maximum;
System.out.println("max is = " + max);
}
}
public static void main(String[] args) throws InterruptedException {
ProcessFileListener listener = new Start();
for (int i = 0; i <= 10; i++) {
for (int j = 0; j <= 5; j++) {
ProcessFile pf = new ProcessFile(listener, i, j);
new Thread(pf).start();
}
}
}
}
请注意,done()
方法是synchronized
,即它是线程安全的。这是因为您可能需要从多个线程访问相同的变量(在这种情况下为max
)。