jstack 死锁 死循环 线程阻塞

1.死循环:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        while (true) {

        }
    }
}

1.jps找出所属进程的pid:


10228268-192f9742a18e4ce5.png
image.png

2.使用jstack找到跟代码相关的线程,为main线程,处于runnable状态,在main方法的第9行,也就是我们死循环的位置:


10228268-e70c1ff0392b0776.png
image.png

10228268-a18993aeab33db6a.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());

    }
}
10228268-0241cb41d4caf187.png
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));
        }

    }
}
10228268-d414e852dc7207ea.png
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。");

    }
}
10228268-55f44d873275d479.png
image.png

猜你喜欢

转载自blog.csdn.net/weixin_33883178/article/details/87105018
今日推荐