1.死循环:
public class Test {
public static void main(String[] args) throws InterruptedException {
while (true) {
}
}
}
1.jps找出所属进程的pid:
image.png
2.使用jstack找到跟代码相关的线程,为main线程,处于runnable状态,在main方法的第9行,也就是我们死循环的位置:
image.png
image.png
2.等待情况:
class TestTask implements Runnable {
@Override
public void run() {
synchronized (this) {
try {
//等待被唤醒
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
ExecutorService ex = Executors.newFixedThreadPool(1);
ex.execute(new TestTask());
}
}
image.png
3.死锁:
class TestTask implements Runnable {
private Object obj1;
private Object obj2;
private int order;
public TestTask(int order, Object obj1, Object obj2) {
this.order = order;
this.obj1 = obj1;
this.obj2 = obj2;
}
public void test1() throws InterruptedException {
synchronized (obj1) {
//建议线程调取器切换到其它线程运行
Thread.yield();
synchronized (obj2) {
System.out.println("test。。。");
}
}
}
public void test2() throws InterruptedException {
synchronized (obj2) {
Thread.yield();
synchronized (obj1) {
System.out.println("test。。。");
}
}
}
@Override
public void run() {
while (true) {
try {
if(this.order == 1){
this.test1();
}else{
this.test2();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
ExecutorService ex = Executors.newFixedThreadPool(10);
// 起10个线程
for (int i = 0; i < 10; i++) {
int order = i%2==0 ? 1 : 0;
ex.execute(new TestTask(order, obj1, obj2));
}
}
}
image.png
4.等待IO
public class Test {
public static void main(String[] args) throws InterruptedException, IOException {
InputStream is = System.in;
int i = is.read();
System.out.println("exit。");
}
}
image.png
网友评论