1. 开启一个线程 把jvm参数 设为-Xmx16
package jvm;
import java.util.ArrayList;
/**
* @author WeiChuanBao
* @date 2022/8/27 20:26
*
*1.当发送oom异常的时候,其他线程会不会挂掉
*
*/
public class _01_threadIsAlive {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
new Thread(()->{
while (true) {
byte[] bytes = new byte[1024 * 1024];
list.add(bytes);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
},"001").start();
}
}
在执行这串代码的时候通过返回结果可以看到 执行完事jvm直接就停下来了
2. 开启两个线程 一个线程让其发生oom 另一个让他正常运行 看能否正常运行
package jvm;
import java.util.ArrayList;
/**
* @author WeiChuanBao
* @date 2022/8/27 20:26
*
*1.当发送oom异常的时候,其他线程会不会挂掉
*
*/
public class _01_threadIsAlive {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
new Thread(()->{
while (true) {
byte[] bytes = new byte[1024 * 1024];
list.add(bytes);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
},"001").start();
new Thread(()->{
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
},"002").start();
}
}
通过执行结果可以看到 虽然已经发生了oom异常 但是 其他线程并没有受到影响
3. 开启两个线程 让一个线程发生oom 另一个线程设置为守护线程
package jvm;
import java.util.ArrayList;
/**
* @author WeiChuanBao
* @date 2022/8/27 20:26
*
*1.当发送oom异常的时候,其他线程会不会挂掉
*
*/
public class _01_threadIsAlive {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<>();
new Thread(()->{
while (true) {
byte[] bytes = new byte[1024 * 1024];
list.add(bytes);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
},"001").start();
Thread thread= new Thread(()->{
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
},"002");
thread.setDaemon(true); 设为守护线程
thread.start();
}
}
可以看到 将第二个线程设置为守护线程后 当第一个线程发生OOM的时候 第二个线程也结束了