move code to correct place

add Thread state related code
This commit is contained in:
2025-02-20 14:17:35 +08:00
parent 2a2707c4e7
commit 400981a341
7 changed files with 64 additions and 5 deletions

View File

@ -0,0 +1,20 @@
package threaddemo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
public class MultiThreadDemo {
public static void main(String[] args) {
ThreadMXBean threadMXBean = java.lang.management.ManagementFactory.getThreadMXBean();
// 不需要获取同步的 monitor 和 synchronizer 信息,仅获取线程和线程堆栈信息
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
// 遍历线程信息,仅打印线程 ID 和线程名称信息
for (ThreadInfo threadInfo : threadInfos) {
System.out.println(STR."[\{threadInfo.getThreadId()}] \{threadInfo.getThreadName()}; Thread state: \{threadInfo.getThreadState()} ; Is daemon: \{threadInfo.isDaemon()}"
);
}
}
}

View File

@ -0,0 +1,34 @@
package threaddemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessDemo {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec(new String[]{"ls","-l", "/home/admin"});
// 读取标准输出
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = stdInput.readLine()) != null) {
System.out.println("标准输出: " + line);
}
// 读取错误输出
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stdError.readLine()) != null) {
System.out.println("错误输出: " + line);
}
// 等待进程结束
int exitCode = p.waitFor();
System.out.println("进程结束,退出码: " + exitCode);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,44 @@
package threaddemo;
public class ThreadLocalDemo {
public ThreadLocal<Integer> localVar = new ThreadLocal<>();
private Integer integer = 0;
public void add() {
integer = integer + 1;
}
public int get() {
return integer;
}
public static void main(String[] args) {
ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();
threadLocalDemo.localVar.set(threadLocalDemo.integer);
Thread t1 = new Thread(threadLocalDemo::add, "t1");
Thread t2 = new Thread( () -> {
threadLocalDemo.add();
threadLocalDemo.localVar.set(threadLocalDemo.get());
System.out.println("value in new thread: " + threadLocalDemo.get());
System.out.println("value in new thread localVar: " + threadLocalDemo.localVar.get());
}, "t2");
t1.start();
t2.start();
try {
t1.join();
System.out.println("value in main thread: " + threadLocalDemo.get());
System.out.println("value in main thread localVar: " + threadLocalDemo.localVar.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,66 @@
package threaddemo;
/**
* 类ThreadShareVariable演示了线程间共享变量的使用和潜在风险
*/
public class ThreadShareVariable {
/**
* 共享变量i多个线程会访问和修改这个变量
*/
public Integer i = 0;
/**
* 设置共享变量i的值
*
* @param i 新的变量值
*/
public void setI(int i) {
this.i = i;
}
/**
* 获取共享变量i的值
*
* @return 当前的变量值
*/
public int getI() {
return i;
}
/**
* 主函数演示了如何在多线程环境下使用共享变量,并展示了线程局部变量的用法
*
* @param args 命令行参数
*/
public static void main(String[] args) {
ThreadShareVariable threadShareVariable = new ThreadShareVariable();
// 使用ThreadLocal以线程为单位隔离变量i的值避免共享变量的并发问题
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(threadShareVariable::getI);
// 新建一个线程该线程会修改共享变量i的值
Thread thread = new Thread(() -> {
threadShareVariable.setI(1);
});
// 新建一个线程该线程会打印共享变量i的值
new Thread(() -> {
System.out.println("print i in new thread: " + threadShareVariable.getI());
}).start();
thread.start();
try {
// 等待线程thread执行完毕
thread.join();
// 打印共享变量i的值预期为1
System.out.println(threadShareVariable.getI());
// 打印ThreadLocal中的值此处的值是最原始的共享变量值0
System.out.println("value in ThreadLocal: " + threadLocal.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,35 @@
package threaddemo;
public class ThreadStateWithJoin {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread t2 = new Thread(() -> {
try {
System.out.println("t2 start");
t1.join(100);
t1.join();
System.out.println("t2 end");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t1.start();
t2.start();
Thread.sleep(20);
System.out.println(STR."t2 state: \{t2.getState()}");
Thread.sleep(100);
System.out.println(STR."t2 state: \{t2.getState()}");
}
}

View File

@ -0,0 +1,19 @@
package threaddemo;
public class ThreadStateWithSync {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (ThreadStateWithSync.class) {
System.out.println("t1 get lock ");
}
});
synchronized (ThreadStateWithSync.class) {
t1.start();
Thread.sleep(100L);
System.out.println(STR."t1 state: \{t1.getState()}");
}
}
}

View File

@ -0,0 +1,42 @@
package threaddemo;
import java.lang.ref.WeakReference;
public class WeakReferenceExample {
public static void main(String[] args) {
Object obj = new Object();
//创建一个弱引用,指向该对象
WeakReference<Object> weakRef = new WeakReference<>(obj);
//手动调用垃圾回收
System.gc();
//检查弱引用是否被回收
if (weakRef.get() == null) {
System.out.println("Weak reference has been collected.");
} else {
System.out.println("Weak reference still exists.");
}
//清除强引用
obj = null;
if (weakRef.get() == null) {
System.out.println("Weak reference has been collected.");
} else {
System.out.println("Weak reference still exists.");
}
//再次手动调用垃圾回收
System.gc();
//再次检查弱引用是否被回收
if (weakRef.get() == null) {
System.out.println("Weak reference has been collected.");
} else {
System.out.println("Weak reference still exists.");
}
}
}