多个方法调用中使用Java本机访问多个Java线程
问题描述:
我呼吁例如在使用JNA C++库这需要输入参数,并连接到服务器并返回服务对象所执行getServer()方法。我正在使用不同的Java线程调用本地方法。这个本地方法使用了一些全局变量,其中实现了本地方法。多个方法调用中使用Java本机访问多个Java线程
我已经宣布在Native.h文件作为Native.cpp文件的extern“C”和实现本地方法的本地方法。这种方法是独立的方法,即不是任何类别或结构的一部分。
所以我的查询这里,如果有一些全局变量存在于Native.cpp,是他们的价值正在从它调用相同的本地方法不同的Java线程改变了吗?
答
是他们的价值正在从它调用相同的本地方法不同的Java线程改变了吗?
当然,全局变量将所有虚拟机共享然后通过线程为好,让我们写一个非常简单的例子来证明:
counter.c中
#include<stdio.h>
int counter = 0;
int incrementAndGet(){
counter++;
return counter;
}
调用它在使用JNA
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();
输出
的javathread=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点,在这两个是没有必要的,那么如果你是刚刚从全局变量读取值,那么你一定不要担心并发。
如果你的方法被执行getter和setter全局变量然后是值变化的方法。 – Lokesh
我很想来标记这是重复[并发问题,同时呼吁通过JNA本机库(https://*.com/questions/6983007/concurrency-issue-while-calling-a-native-library-通过JNA),因为它间接回答你的问题,并提供解决方法。同意这回答你的问题? –
@ErwinBolwidt: - 所提到的链接解释如何从Java调用同步到本地。但在我的情况,我想知道全局变量是存在于本地文件。 – Prashant