多个Java线程使用Java Native Access进行多个方法调用

时间:2017-10-11 08:48:38

标签: java c++ multithreading jna

我要求例如使用JNA在C ++库中实现的getServer()方法,它接受输入参数并连接到服务器并返回服务器对象。我使用不同的Java线程调用上面的本机方法。这个本机方法使用了一些全局变量,其中实现了本机方法。

我已将Native.h文件中的本机方法声明为extern“C”并在Native.cpp文件中实现本机方法。此方法是独立方法,即不属于任何类或结构的一部分。

所以我的查询是,如果Native.cpp中存在一些全局变量,它们的值是否会从调用相同本机方法的不同Java线程更改?

1 个答案:

答案 0 :(得分:0)

  

它们的值是否从调用相同本机方法的不同Java线程更改?

当然,全局变量将由所有虚拟机共享,然后由线程共享,让我们写一个非常简单的例子来证明:

counter.c中

#include<stdio.h>

int counter = 0;
int incrementAndGet(){
    counter++;
    return counter;
}

使用JNA在java中调用它

final ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 20; i++) {
    executorService.submit(() -> {
        try {
            TimeUnit.MILLISECONDS.sleep((long) (Math.random() * 1000));
        } catch (InterruptedException e) {}
        System.out.printf("thread=%s, counter=%d%n", Thread.currentThread().getName(), CounterLib.INSTANCE.incrementAndGet());
    });
}
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdown();

输出

thread=pool-1-thread-2, counter=1
thread=pool-1-thread-4, counter=2
thread=pool-1-thread-1, counter=3
thread=pool-1-thread-5, counter=4
thread=pool-1-thread-2, counter=5
thread=pool-1-thread-3, counter=6
thread=pool-1-thread-2, counter=7
thread=pool-1-thread-4, counter=8
thread=pool-1-thread-1, counter=9
thread=pool-1-thread-2, counter=10
thread=pool-1-thread-5, counter=11
thread=pool-1-thread-3, counter=12
thread=pool-1-thread-5, counter=13
....

你也必须担心这个全局变量的并发性,或者在java或c中,两者都没有必要,那么如果你只是从全局变量中读取值,那么你就不必担心并发。