move code to correct place

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

View File

@ -1,3 +1,5 @@
package threaddemo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
@ -11,10 +13,7 @@ public class MultiThreadDemo {
// 遍历线程信息仅打印线程 ID 和线程名称信息
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "] "
+ threadInfo.getThreadName()
+ "; Thread state: " + threadInfo.getThreadState()
+ " ; Is daemon: " + threadInfo.isDaemon()
System.out.println(STR."[\{threadInfo.getThreadId()}] \{threadInfo.getThreadName()}; Thread state: \{threadInfo.getThreadState()} ; Is daemon: \{threadInfo.isDaemon()}"
);
}
}

View File

@ -1,3 +1,5 @@
package threaddemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

View File

@ -1,3 +1,5 @@
package threaddemo;
public class ThreadLocalDemo {
public ThreadLocal<Integer> localVar = new ThreadLocal<>();

View File

@ -1,4 +1,4 @@
import java.util.stream.DoubleStream;
package threaddemo;
/**
* 类ThreadShareVariable演示了线程间共享变量的使用和潜在风险

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

@ -1,3 +1,5 @@
package threaddemo;
import java.lang.ref.WeakReference;
public class WeakReferenceExample {