cd glibc-2.19
编译完成后要存放的文件位置:
mkdir out
编译 (完成后覆盖系统默认的文件, 请提前备份默认文件, 以防不测)
- cd out
- ../configure --prefix=/usr --disable-profile --enable-add-ons --with-headers=/usr/include --with-binutils=/usr/bin
执行:
make //make 执行完毕之后再执行 make install
测试 运行:
java
只有调用了 pthread_mutex_lock() 会打印出自己的线程 id:
表示此处修改 Linux 源码 glibc 库下的 pthread_mutex_lock() 成功;
接下来就该验证偏向锁到底是不是真实存在的:
java 代码:
import java.lang.Thread; public class ThreadTest { Object o= new Object(); static { System.loadLibrary( "TestThreadNative" ); } public static void main(String[] args) { // 打印出主线程 System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxx"); ThreadTest example4Start = new ThreadTest(); example4Start.start(); } public void start(){ Thread thread = new Thread(){ @Override public void run() { while (true){ try { sync(); } catch (InterruptedException e) { } } } }; Thread thread2 = new Thread(){ @Override public void run() { while (true){ try { sync(); } catch (InterruptedException e) { e.printStackTrace(); } } } }; thread.setName("t1"); thread2.setName("t2"); thread.start(); } //.c 文件打印出 java threaid 对应的 os threadid public native void tid(); public void sync() throws InterruptedException { synchronized(o) { //java threadid 是 jvm 给的线程 id 并不是真是的 os 对应的线程 id //System.out.println(Thread.currentThread().getId()); // 获取 java thread 对应的真实的 os thread 打印出 id tid(); } } }
获取真实线程 id(os 线程 Id) 的 c 文件:(对应上边 java 代码的 native void tid())
#include<pthread.h> #include<stdio.h> #include<stdlib.h> #include "Example4Start.h" JNIEXPORT void JNICALL Java_Example4Start_tid(JNIEnv *env, jobject c1){ printf("current tid:%lu-----\n",pthread_self()); usleep(700); }
然后再走一遍生成. class,.h ,so 然后执行 (此方法在 [java 并发笔记之 java 线程模型] 链接: https://www.cnblogs.com/yuhangwang/p/11256476.html 中有相对应执行方法, 请参考)
执行:
java ThreadTest
显示:
实锤: 红色的证明偏向锁真实存在, 绿色的证明 synchronized 1.6 之后偏向锁做了优化 (只调用了一次 os 函数, 后面没有调用)
同理轻量级锁及重量级锁也可以这样证明出来
来源: https://www.cnblogs.com/yuhangwang/p/11258599.html