add demo for volatile keyword and Class loader

This commit is contained in:
=
2025-08-17 01:01:43 +08:00
parent 4c5eb89e59
commit 16cbb1a8a0
2 changed files with 98 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
package jvm;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class VolatileTest {
public static volatile int race = 0;
private static final Object lock = new Object();
private static final ReentrantLock lock1 = new ReentrantLock();
public static AtomicInteger race1 = new AtomicInteger(0);
public static void increase() {
// synchronized (lock) {
// race++;
// }
race1.getAndAdd(1);
lock1.lock();
race++;
lock1.unlock();
}
private static final int THREADS_COUNT = 20;
static void main() {
Thread[] threads = new Thread[THREADS_COUNT];
for (int i = 0; i < THREADS_COUNT; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
increase();
}
});
threads[i].start();
}
// for idea only. otherwise should be 1
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println(race);
System.out.println(race1.get());
}
}

View File

@@ -0,0 +1,56 @@
package loader;
import java.io.*;
public class CustomLoader extends ClassLoader{
private String classPath;
public CustomLoader(String classPath) {
this.classPath = classPath;
}
private byte[] loadClassBytes(String className) {
String path = STR."\{classPath}\{File.separatorChar}\{className.replace('.', File.separatorChar)}.class".trim();
// File file = new File("C:\\Users\\wjluk\\projects\\java_multithread\\src\\main\\java\\loader\\LoaderTest.class");
File file = new File(path);
System.out.println(file.exists());
try (InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
return baos.toByteArray();
} catch (IOException e) {
return null;
}
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classBytes = loadClassBytes(name);
if (classBytes == null) {
throw new ClassNotFoundException();
}
return defineClass(name, classBytes, 0, classBytes.length);
}
static void main(String[] args) throws Exception {
CustomLoader loader = new CustomLoader(" D:\\");
Class<?> clazz = loader.loadClass("LoaderTest");
Object obj = clazz.newInstance();
clazz.getMethod("greeting").invoke(obj);
System.out.println(clazz.getClassLoader());
System.out.println("---------------------for parent loader-------------------");
ClassLoader classLoader = loader.getClass().getClassLoader();
while (classLoader != null) {
System.out.println( "\t" + classLoader);
classLoader = classLoader.getParent();
}
}
}