---
title: "关于Java多线程通过jni调用C方法的注意事项"
author: "eleopard"
date: "2010-11-25T18:35:59Z"
tags: []
categories: ["编程语言"]
slug: "java-jni-c"
draft: false
lastmod: "2010-11-25T18:46:15Z"
id: 824793
url: "https://eleopard.iteye.com/blog/824793"
---

JNI定义如下

```java
package jni;   
public class Test {   
    public native void addOne();   
    public native int getGlobalValue();   
}  
```


JNI对应的C代码

```C
#include"jni_Test.h"   
#include <stdio.h>   
int value = 1000;   
JNIEXPORT void JNICALL Java_jni_Test_addOne(JNIEnv *env, jobject obj)
{   
    value = value +1;   
}   
JNIEXPORT jint JNICALL Java_jni_Test_getGlobalValue(JNIEnv *env, jobject obj)   
{   
    return value;   
} 
```


创建多个线程操作全局变量

```java
package jni;
public class MainCygwin {
    static{
        System.loadLibrary("test");
    }
    public static void main(String[] args) {
        Test hl = new Test();
        Thread t1 = new Thread(new Add("first",hl));
        Thread t2 = new Thread(new Add("second",hl));
        t1.start();
        t2.start();
    }
}
class Addimplements Runnable{
    private String name;
    private Test hl;   
    public Add(String name,Test hl)   
    {   
        this.name = name;
        this.hl = hl;   
    }   
    @Override  
    public void run() {   
        int i = 0;    
        while(i < 100)   
        {   
            i++;   
            h1.addOne(); 
            System.out.println(this.name + hl.getGlobalValue());
            try {   
                Thread.sleep(10);   
            } catch (InterruptedException e) {   
                e.printStackTrace();   
            }   
        }   
    } 
} 
```


<span style="color:red">两个加操作线程操作的是同一个value变量</span>