我有一个类,它有一个方法,它为大多数工作服务。我想对这个方法进行多次调用,同时运行它(同时进行多个搜索)。我想要调用的方法使用了类的本地属性,因此我不能简单地创建一个包含此方法的新类,因为它将无法访问其他类的属性,因为它们具有不同的内存空间。
示例:
class mainWork {
static int localInt;
static String testString;
public static void main(){
new Runnable(){
public void run(){
doWork();
}
}.run();
}
public void doWork(){
localInt = 1;
testString = "Hi";
}
}创建匿名可运行的内部类不能工作,因为该线程无法访问mainWorks属性。如果我创建一个单独的类,扩展线程--我也有同样的问题。是否有一种方法(可能根本不使用线程),我可以调用一个方法,它仍然可以访问在运行同时调用它的类中的属性?我想一次给doWork打很多次电话,以加快操作速度。也许是任务?
发布于 2017-05-15 10:53:39
您的代码中有许多问题:
() -> doWork();;的末尾使用new Runnable() {...};testString = "Hi";您的代码应该如下所示:
int localInt;
String testString;
public static void main(String[] args) {
new Runnable() {
public void run() {
MainWork a = new MainWork();
a.doWork();
}
};
}
public void doWork() {
localInt = 1;
testString = "Hi";
}直到现在,您的程序将编译,但什么也不做,启动您的线程您必须使用:
Runnable r = new Runnable() {
@Override
public void run() {
MainWork a = new MainWork();
a.doWork();
}
};
new Thread(r).start();还有一点,不要在类mainWork的名字中使用小写字母,而必须使用MainWork
发布于 2017-05-15 11:15:41
受到您的问题的启发,我做了这个处理并行处理的简短示例,而不关心线程,这是一个“非阻塞代码”,可以更容易地实现。
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
*JAVA 8 introduces a new concept for dealing with concurrencies
*CompletableFuture
*/
class MainWork {
static int localInt;
static String testString;
public static void main(String args[]) throws IOException {
CompletableFuture.supplyAsync(MainWork::doWork).thenAccept(System.out::println);
System.in.read(); //this line is only to keep the program running
}
public static List<String> doWork() {
localInt = 100;
testString = "Hi";
List<String> greetings = new ArrayList<String>();
for (int x = 0; x < localInt; x++) {
greetings.add(testString);
}
return greetings;
}
}https://stackoverflow.com/questions/43977532
复制相似问题