java 如何使用Java在同一个类中同时运行2个方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43331960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 07:20:31  来源:igfitidea点击:

How to run 2 methods concurrently in same class with Java

javamultithreadingconcurrency

提问by Emre Danisan

I would like to use 2 methods in the same class concurrently using the same object in Java. For example:

我想在 Java 中同时使用同一个对象在同一个类中使用 2 个方法。例如:

public class aThread extends Thread {

    int countA = 0;
    int countB = 0;

    int countA(){
        for (int i = 0; i < 1000; i++) {
            countA++;
        }
        return countA;
    }
    int countB(){
        for (int i = 0; i < 1000; i++) {
            countB++;
        }
        return countB;
    }
    @Override
    public void run() {
        super.run(); 
        //should there be something here?
    }
}

And using this methods in another method:

并在另一种方法中使用此方法:

public class MainClass {

    public static void main(String[] args) {

        aThread myThread = new aThread();

        myThread.countA(); //I want these 2 methods to run concurrently.
        myThread.countB();
        //how do I use myThread.start() here?

    }
}

note: They don't have to be synchronized.

注意:它们不必同步。

回答by Andrii Abramov

There are several ways to achieve your task. You have quiet easy situation when threads should not be synchronized.

有多种方法可以完成您的任务。当线程不应该同步时,您会遇到安静的轻松情况。

You can use ExecutorServicefrom Java Concurrency:

您可以ExecutorService从 Java Concurrency 中使用:

public class ConcurrentCode {

    private int countA = 0;
    private int countB = 0;

    int countA(){
        for (int i = 0; i < 1000; i++) {
            countA++;
        }
        System.out.println(countA);
        return countA;
    }

    int countB(){
        for (int i = 0; i < 1000; i++) {
            countB++;
        }
        System.out.println(countB);
        return countB;
    }

    public void execute(){
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        // method reference introduced in Java 8
        executorService.submit(this::countA);
        executorService.submit(this::countB);

        // close executorService
        executorService.shutdown();
    }


    public static void main(String[] args){
        new ConcurrentCode().execute();
    }

}

Remember to close ExecutorServiceotherwise your application won't stop because it will have alive threads.

请记住关闭,ExecutorService否则您的应用程序将不会停止,因为它将有活动线程。

Or you can have the simplest approach using vanilla Java threads:

或者您可以使用普通Java 线程采用最简单的方法:

public void executeInNativeThreads(){

    // starts new thread and executes countA in it
    new Thread(this::countA).start();

    // starts new thread and executes countB in it
    new Thread(this::countB).start();

}

To get computation results you can get the Future<Integer>from executorServiceand then you have a choice:

要获得计算结果,你可以得到Future<Integer>fromexecutorService然后你有一个选择:

  • poll Futureif it is done
  • wait until the Futurewill be completed.
  • wait explicitly for certain timeout
  • 投票Future是否完成
  • 等到Future将完成。
  • 明确等待特定超时

Here is an example:

下面是一个例子:

public void execute() throws Exception {
    ExecutorService executorService = Executors.newFixedThreadPool(2);

    Future<Integer> future1 = executorService.submit(this::countA);
    Future<Integer> future2 = executorService.submit(this::countB);

    // wait until result will be ready
    Integer result1 = future1.get();

    // wait only certain timeout otherwise throw an exception
    Integer result2 = future2.get(1, TimeUnit.SECONDS);

    System.out.println("result1 = " + result1);
    System.out.println("result2 = " + result2);

    executorService.shutdown();
}

Note, while we are explicitly waiting for result of future1, future2is still being executed in another thread. It means that there won't be big delay in computation of future2in particularly this example.

请注意,虽然我们正在显式等待 的结果future1future2但仍在另一个线程中执行。这意味着future2特别是这个例子的计算不会有很大的延迟。

Also, take a look at CompletionStagewhich is used in asynchronous computations.

另外,请查看异步计算中使用的CompletionStage

回答by DJAM Silvère Gatien

To run your code concurrently, you need at least two threads :

要同时运行您的代码,您至少需要两个线程:

public class MyClass {

    int countA = 0;
    int countB = 0;

    public int countA(){
        for (int i = 0; i < 1000; i++) {
            countA++;
        }
        return countA;
    }

    public int countB(){
        for (int i = 0; i < 1000; i++) {
            countB++;
        }
        return countB;
    }

    public static void main(String[] args) throws Exception{
        MyClass myClass = new MyClass() ;
        ExecutorService  executorService = Executors.newFixedThreadPool(2) ;
        List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>() ;
        tasks.add(myClass::countA) ;
        tasks.add(myClass::countB) ;
        List<Future<Integer>> results = executorService.invokeAll(tasks) ;
        System.out.println(results.get(0).get()+" "+results.get(1).get());
        executorService.shutdown();
    }
}

You can track the result with: results.

您可以使用以下方法跟踪结果:results。

回答by ControlAltDel

You need to create Runnables to invoke the methods you are trying to run concurrently within independent threads

您需要创建 Runnables 来调用您尝试在独立线程中并发运行的方法

public static void main(String[] args) {
  final aThread myThread = new aThread();

  Runnable a = new Runnable() {
    public void run() {
      myThread.countA();
    }
  });
  Runnable b = new Runnable() {
    public void run() {
      myThread.countB();
    }
  });
    new Thread(a).start();
    new Thread(b).start();
}