并发方法

时间:2017-05-15 10:47:29

标签: java multithreading

我有一个类,有一个方法可以完成大部分工作。我想对这个方法进行多次调用,同时运行它(同时进行多次搜索)。我想要调用的方法使用我的类的本地属性,因此我无法使用此方法创建一个新类,因为它无法访问我的其他类'属性因为它们有不同的内存空间。

示例:

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";
    }
}

创建匿名Runnable内部类不起作用,因为该线程无法访问mainWorks属性。如果我创建一个单独的类,扩展Thread我有同样的问题。有没有办法(可能根本就没有使用线程)我可以调用一个方法,该方法仍然可以访问同时调用时调用它的类中的属性?我想一次多次调用doWork来加速操作。任务可能吗?

2 个答案:

答案 0 :(得分:1)

您的代码中存在许多问题:

  • 错误的主要方法声明
  • 要调用方法,您必须使用() - > doWork();
  • 您必须在声明;
  • 的末尾使用new Runnable() {...};
  • 您无法将字符串分配给int 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

答案 1 :(得分:0)

受到你的问题的启发,我做了一个简短的例子来处理并行处理而不关心线程,这是一个非阻塞代码"这可以更容易实现。

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;
    }
}