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

Emr*_*san 2 java concurrency multithreading

我想在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?
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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?

    }
}
Run Code Online (Sandbox Code Playgroud)

注意:它们不必同步.

And*_*mov 7

有几种方法可以完成您的任务.当线程不同步时,您可以轻松安静.

您可以使用ExecutorServiceJava 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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

或者您可以使用最简单的方法使用vanilla 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();

}
Run Code Online (Sandbox Code Playgroud)

为了让计算结果就可以得到Future<Integer>executorService然后你有一个选择:

  • Future如果完成则进行轮询
  • 等到Future将完成.
  • 明确等待某些超时

这是一个例子:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

另外,看看在异步计算中使用的CompletionStage.